1 / 56

PART I THE C# LANGUAGE

PART I THE C# LANGUAGE. Chapters 1,2. Chapter 1- .NET Architecture. Compiling and running code that targets .NET Advantages of Microsoft Intermediate Language (MSIL) Value and reference types Data typing Understanding error handling and attributes

zinnia
Télécharger la présentation

PART I THE C# LANGUAGE

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. PART I THE C# LANGUAGE Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al Chapters 1,2

  2. Chapter 1- .NET Architecture • Compiling and running code that targets .NET • Advantages of Microsoft Intermediate Language (MSIL) • Value and reference types • Data typing • Understanding error handling and attributes • Assemblies, .NET base classes, and namespaces Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  3. Relationship of C# to .NET • C# is a relatively new programming language and is significant in two respects: • It is specifically designed and targeted for use with Microsoft’s .NET Framework (a feature – rich platform for the development, deployment, and execution of distributed applications). • It is a language based on the modern object- oriented design methodology • C# is a language in its own right. Although it is designed to generate code that targets the .NET environment, it is not itself part of .NET • Some features are supported by .NET but not by C# and vice versa (Eg: some instances of operator overloading are not supported by .NET but are by C#. Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  4. Common Language Runtime Central to the .NET Framework is its runtime execution environment, known as the Common Language Runtime (CLR) or the .NET runtime. Code running under the control of the CLR is often termed managed code. Compilation occurs in two steps in .NET: • Compilation of source code to Microsoft Intermediate Language (IL). • Compilation of IL to platform-specific code by the CLR. Advantages • Platform Independence • Performance Improvement • Language Interoperability Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  5. Key features of IL • Object orientation and the use of interfaces • Strong distinction between value and reference types Value types are those for which a variable directly stores its data, whereas reference types are those for which a variable simply stores the address at which the corresponding data can be found. • Strong data typing All variables are clearly marked as being of a particular, specific data type. In particular, IL does not normally permit any operations that result in ambiguous data types. Eg: variant • Error handling using exceptions • Use of attributes Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  6. Language interoperability Language interoperability is that classes written in one language should be able to talk directly to classes written in another language. • A class written in one language can inherit from a class written in another language. • The class can contain an instance of another class, no matter what the languages of the two classes are. • An object can directly call methods against another object written in another language. • Objects (or references to objects) can be passed around between methods. • When calling methods between languages, you can step between the method calls in the debugger, even when this means stepping between source code written in different languages. Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  7. Strong Data Typing The services provided by .NET that rely on type safety: • Language interoperability • Garbage collection • Security • Application domains Common Type System The CTS defines the predefined data types that are available in IL, so that all languages that target the .NET Framework will produce compiled code that is ultimately based on these types. Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  8. Common Language Specification • The Common Language Specification (CLS) works with the CTS to ensure language interoperability. • The CLS is a set of minimum standards that all compilers targeting .NET must support. • Because IL is a very rich language, writers of most compilers will prefer to restrict the capabilities of a given compiler to support only a subset of the facilities offered by IL and the CTS. • For example, IL is case-sensitive. CLS compliant code should not expose any two names that differ only in their case Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  9. Garbage Collection • The garbage collector is .NET ’ s answer to memory management and in particular to the question of what to do about reclaiming memory that running applications ask for. • Garbage collection works in .NET because IL has been designed to facilitate the process. • The principle requires that you cannot get references to existing objects other than by copying existing references and that IL be type safe. • One important aspect of garbage collection is that it is not deterministic , i.e. the time its called is unpredictable. Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  10. Security • .NET can really excel in terms of complementing the security mechanisms provided by Windows because it can offer code-based security, whereas Windows really offers only role-based security. • Role-based security is based on the identity of the account under which the process is running (that is, who owns and is running the process). • Code-based security, by contrast, is based on what the code actually does and on how much the code is trusted. • The importance of code-based security is that it reduces the risks associated with running code of dubious origin Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  11. Application Domains • Application domains are an important innovation in .NET and are designed to ease the overhead involved when running applications that need to be isolated from each other but that also need to be able to communicate with each other. • Example: A web server application, which may be simultaneously responding to a number of browser requests • Application domains are designed as a way of separating components without resulting in the performance problems associated with passing data between processes Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  12. Use of Exceptions and Attributes Error Handling With Exceptions • The exception architecture ensures that when an error condition occurs, execution can immediately jump to the exception handler routine that is most specifically geared to handle the exception condition in question. Use Of Attributes • The initial idea of an attribute was that it provided extra information concerning some item in the program that could be used by the compiler. • Attributes can be defined in source code in one language and read by code that is written in another language. Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  13. Assemblies • An assembly is the logical unit that contains compiled code targeted at the .NET Framework. • An assembly is completely self - describing and is a logical rather than a physical unit, which means that it can be stored across more than one file. • An important characteristic of assemblies is that they contain metadata that describes the types and methods defined in the corresponding code. • An assembly, however, also contains assembly metadata that describes the assembly itself. This assembly metadata, contained in an area known as the manifest. • Assemblies come in two types: private and shared assemblies. Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  14. Types of Assemblies • Privateassemblies are the simplest type. They normally ship with software and are intended to be used only with that software. • Sharedassemblies are intended to be common libraries that any other application can use. Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  15. Reflection Reflection is the technique used by managed code to actually examine other managed code, and even examine itself, to determine information about that code. Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  16. Parallel and Asynchronous Programming • Parallel Programming allows work actions to run across multiple processors • The new parallel programming APIs that are available now make writing safe multi-threaded code simple • Asynchronous Programming allows tasks to run independently, without blocking the main program (i.e. a UI thread processing an asynchronous task would not have to wait and become unresponsive) • Asynchronous methods have become much easier to invoke in the latest release of .NET due to the Task Parallel Library (TPL) Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  17. .Net Framework Classes • The .NET base classes are a massive collection of managed code classes. • These classes follow the same object model that IL uses, based on single inheritance. • The great thing about the .NET base classes is that they have been designed to be very intuitive and easy to use. For example, to start a thread, you call the Start( ) method of the Thread class. • For calling an API function not available in the base classes, .NET offers a platform – invoke that ensures data types are correctly converted. Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  18. Namespaces • Namespaces are the way that .NET avoids name clashes between classes. • A namespace is no more than a grouping of data types, but it has the effect that the names of all data types within a namespace are automatically prefixed with the name of the namespace. • It is also possible to nest namespaces within each other. • If a namespace is not explicitly supplied, the type will be added to a nameless global namespace. • Microsoft recommends that for most purposes you supply at least two nested namespace names; the first represents the name of your company and the second represents the name of the technology or software package • CompanyName.SalesServices.Customer Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  19. Creating .NET Applications Using C# Console Applications • C# can be used to create console applications: text - only applications that run in a DOS window. ASP.NET Applications • The primary goal of ASP.NET is to build powerful, secure, dynamic applications using the least possible amount of code. Windows forms • Windows forms support fat-client or thick-client apps — applications that must be installed on the end user’s machine where most of the processing takes place. Windows Presentation Foundation (WPF) • WPF makes use of XAML, the XML declaration of an application, to create the visual aspects and behaviors of an application through Declarative Programming • Declarative programming means that instead of creating objects through programming in a compiled language such as C#, VB, or Java, everything is declared through XML-type programming. Windows 8 Apps • Written with C# and XAML to create a touch-first application specific for Windows 8 and newer operating systems. Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  20. Creating ASP.NET Applications Features Of ASP.NET • ASP.NET pages are structured. • ASP.NET pages are easier to understand. • A Visual Studio project, or solution, contains all the files associated with an application. • ASP.NET is remarkable for its increased performance. • Web Forms make web page construction even easier. • Web Server Controls areused to populate a Web Form and are XML tags in the ASP.NET namespace that the web browser dynamically transforms into HTML and client-side script when a page is requested • ASP.NET MVC supports the Model-View-Controller pattern for easily testable applications that can leverage HTML5 and JavaScript libraries • ASP.NET Dynamic Data uses Entity Framework and scaffolding options to efficiently read and write data in a form • ASP.NET Web API allows for a simple communication between the client and server using REST, making it easy to consume data in web clients using JavaScript as well as Windows 8 applications Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  21. Creating Windows Applications Windows Service • A program designed to run in the background. • Services are used when a program has to be running continuously and ready to respond to events without having been explicitly started by the user. Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  22. WCF and WF Windows Communication foundation (WCF) • Single way to move data and services from one point to another. • Supports both REST and SOAP-based communication. • WCF provides an ability to build service one time and then expose this service in a multitude of ways by just making changes within a configuration file. Windows Workflow foundation (WF) • WF provides a model to define and execute processes using a set of building blocks called activities. • A workflow is constructed from a number of activities, and these activities are executed at runtime. Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  23. SUMMARY Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  24. Chapter 2- CORE C# • Variables • Predefined Data types • Flow Control • Enumerations • Namespaces • The Main() method • Compiling methods • Console I/O • Using Comments • Preprocessor directives • Guidelines and conventions for good programming in C# Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  25. First C# program using System; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; namespace Chapter2 { classHello_World { staticvoid Main(string[] args) { Console.WriteLine("Hello World!"); Console.ReadLine(); return; } } } //Code Snippet: Hello_World.cs Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  26. Variables Syntax: datatype identifier; For example: int i; This statement declares an int named i. The compiler won’t actually let you use this variable in an expression until you have initialized it with a value. After it has been declared, you can assign a value to the variable using the assignment operator, =: i = 10; int i = 10; int x = 10, y =20; // x and y are both integers int x = 10, bool y = true; // This won't compile! Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  27. Type Inference Type inference makes use of the varkeyword. The compiler “infers” what type the variable is by what the variable is initialized to. For example, int someNumber = 0; becomes var someNumber = 0; Even though someNumber is never declared as being an int, the compiler figures this out and someNumberis an int for as long as it is in scope. Once compiled, the two preceding statements are equal. Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  28. code snippet: Variables1.cs namespace Variables1_ConsoleApp { classProgram { staticvoid Main(string[] args) { var name = "Bugs Bunny"; var age = 25; varisRabbit = true; TypenameType = name.GetType(); TypeageType = age.GetType(); TypeisRabbitType = isRabbit.GetType(); Console.WriteLine("name is type " + nameType.ToString()); Console.WriteLine("age is type " + ageType.ToString()); Console.WriteLine("isRabbit is type " + isRabbitType.ToString()); Console.ReadLine(); return; } } } Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  29. Variable scope The scope of a variable is the region of code from which the variable can be accessed. In general, the scope is determined by the following rules: • A field (also known as a member variable) of a class is in scope for as long as its containing class is in scope. • A local variable is in scope until a closing brace indicates the end of the block statement or method in which it was declared. • A local variable that is declared in a for, while, or similar statement is in scope in the body of that loop. • A scope clash may occur with local variable declaration. Code Snippet: Scope_Clash.cs • C# makes a fundamental distinction between variables that are declared at the type level (fields) and variables that are declared within methods (local variables) Code Snippet: Scope_Test.cs Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  30. Constants • As the name implies, a constant is a variable whose value cannot be changed throughout its lifetime. const int a = 100; // This value cannot be changed. • Constants make the programs easier to read, modify and help prevent mistakes. classScope_Test { constint a = 100; staticint j = 20; publicstaticvoid Main() { int j = 30; Console.WriteLine(j+a); return; } } OUTPUT: 130 Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  31. Predefined Data Types Value Types And Reference Types • A value type stores its value directly, whereas a reference type stores a reference to the value. • Value types are stored in an area known as the stack, and reference types are stored in an area known as the managed heap. • For example, int is a value type; Vector is a reference type. • The Common Language Runtime (CLR) implements an elaborate algorithm to track which reference variables are still reachable and which have been orphaned. • Periodically, the CLR will destroy orphaned objects and return the memory that they once occupied back to the operating system. This is done by the garbage collector. Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  32. Predefined Value Types Integer Types Floating-point Types Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  33. Predefined Value Types Contd. • The Decimal Type • The Boolean Type • The Character Type Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  34. Predefined Value Types Contd. • Escape sequences Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  35. Predefined Reference Types The object Type • In C#, the object type is the ultimate parent type from which all other intrinsic and user-defined types are derived The string Type • A string object is allocated on the heap, not the stack, and when one string variable is assigned to another string, two references to the same string in memory is obtained. string str1 = "Hello "; string str2 = "World"; string str3 = str1 + str2; // string concatenation Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  36. code snippet : StringExample.cs classStringExample { publicstaticint Main() { string s1 = "a string"; string s2 = s1; Console.WriteLine("s1 is " + s1); Console.WriteLine("s2 is " + s2); s1 = "another string"; Console.WriteLine("s1 is now " + s1); Console.WriteLine("s2 is now " + s2); Console.ReadLine(); return 0; } } Output: s1 is now a string s2 is now a string s1 is now another string s2 is now another string Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  37. Flow Control • The statements that allows to control the flow of the program rather than executing every line of code in the order it appears in the program. Conditional Statements • Conditional statements allow you to branch your code depending on whether certain conditions are met or on the value of an expression. • Two types: if statement and switchstatement. • The if statement allows to test whether a specific condition is met. if (condition) statement(s) else statement(s) Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  38. code snippet: ElseIf.cs classElseif { staticvoid Main(string[] args) { Console.WriteLine("Type in a string"); string input; input = Console.ReadLine(); if (input == "") { Console.WriteLine("You typed in an empty string."); } elseif (input.Length < 5) { Console.WriteLine("The string had less than 5 characters."); } elseif (input.Length < 10) { Console.WriteLine("The string had at least 5 but less than 10Characters."); } Console.WriteLine("The string was " + input); } } Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  39. The switch statement • The switchstatement, which allows to compare an expression with a number of different values. • The end of the code for each case is marked using the breakstatement. • The defaultcase will execute if the expression evaluates to none of the other cases. switch (integerA) { case 1: Console.WriteLine("integerA =1"); break; case 2: Console.WriteLine("integerA =2"); break; case 3: Console.WriteLine("integerA =3"); break; default: Console.WriteLine("integerA is not 1,2, or 3"); break; } Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  40. Loops • C# provides four different loops (for, while, do . . . while, and foreach) that allow to execute a block of code repeatedly until a certain condition is met. • The for loop for (initializer; condition; iterator) statement(s) code snippet NestedFor.cs • The while loop: while(condition) statement(s); • The do . . . while loop do {statement(s); } while(condition); • The foreach loop allows to iterate through each item in a collection. Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  41. Jump Statements C# provides a number of statements that allow to jump immediately to another line in the program. E.g. Break, goto, continue, return. The gotostatement allows to jump directly to another specified line in the program, indicated by a label (this is just an identifier followed by a colon) It certainly doesn’t conform to good object-oriented programming practice. goto Label1; Console.WriteLine("This won't be executed"); Label1: Console.WriteLine("Continuing execution from here"); • The continuestatement exits only from the current iteration of the loop, meaning that execution will restart at the beginning of the next iteration of the loop. • The return statement is used to exit a method of a class, returning control to the caller of the method. Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  42. Enumerations • An enumeration is a user-defined integer type. • The declaration of an enumeration must specify a set of acceptable values that instances of that enumeration can contain. public enum TimeOfDay { Morning = 0, Afternoon = 1, Evening = 2 } • System.Enum has several methods that help in the manipulation of instances of enum. Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  43. Namespaces • Namespaces provide a way of organizing related classes and other types. • Unlike a file or a component, a namespace is a logical rather than physical grouping. • Example: namespace Wrox { namespace ProCSharp { namespace Basics { class NamespaceEx { // Code for the class here... } } } } • Full name of NamespaceExclass is wrox.ProCSharp.Basics.NamespaceEx Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  44. The using directive • The using statements occur at the top of C# files. It does no physical linking between files. • The class’s namespace is listed at the top of the file, prefixed with the using keyword • Namespace aliases: Another use of the usingkeyword is to assign aliases to classes and namespaces. using alias = NamespaceName; Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  45. Main() method • C# programs start execution at a method named Main() • This must be a static method of a class (or struct), and must have a return type of either int or void. • The method can be marked as private or public(more appropriate as it has to be called from outside the program) Multiple Main() Methods: • If there is more than one Main() method in an application, the compiler will return an error message. • In this case the compiler has to be told which of these methods to use as the entry point by using the /main switch, together with the full name of the class to which the Main() method belongs. E.g. cscDoubleMain.cs /main:Wrox.MathExample Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  46. codesnippet: DoubleMain.cs classClient { publicstaticint Main() { MathExample.Main(); return 0; } } classMathExample { staticint Add(int x, int y) { return x + y; } publicstaticint Main() { int i = Add(5, 10); Console.WriteLine(i); return 0; } } //cscDoubleMain.cs /main:Wrox.MathExample to compile Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  47. Compiling C# Files • Example: To compile a C# file into a .NET DLL using the following command, csc/t:libraryMathLibrary.cs Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  48. Console I/O Some of the Console class’s static methods used for reading and writing data: • To read a line of text from the console window, you use the Console.ReadLine() method. • Console.Write()— Writes the specified value to the console window. • Console.WriteLine() — This does the same, but adds a newline character at the end of the output. Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  49. Using Comments Internal comments within the source files: C# uses the traditional C-type single-line (//...) and multiline (/* ... */) comments: // This is a singleline comment /* This comment spans multiple lines. */ Xml documentation • C# has a very neat feature that has the ability to produce documentation in XML format automatically from special comments. • These comments are single-line comments but begin with three slashes (///) • Within these comments, you can place XML tags containing documentation Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

  50. Xml Documentation Reference: Professional C# 2012 and .Net 4.5 by Bill Evjen, et al

More Related