1 / 85

Lecture1 Introduction to C#

Lecture1 Introduction to C#. Instructor: Haya Sammaneh. Contents. Features of C#. Very similar to Java 70% java, 10% C++, 5% Visual Basic, 15% new . New Feature in C#. Visual Studio.NET. VB. C++. C#. JScript. J#. Common Language Specification (CLS). ASP.NET Web Forms Web Services.

michi
Télécharger la présentation

Lecture1 Introduction to C#

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. Lecture1Introduction to C# Instructor: Haya Sammaneh

  2. Contents

  3. Features of C# Very similar to Java 70% java, 10% C++, 5% Visual Basic, 15% new

  4. New Feature in C#

  5. Visual Studio.NET VB C++ C# JScript J# Common Language Specification (CLS) ASP.NET Web Forms Web Services Windows Forms ADO.NET and XML Common Language Runtime (CLR) Operating System .Net Framework

  6. .NET Framework • Building a program in C/C++: –Compile the source code (link it) to create the portable executable (Win32 PE) file. – When the PE is invoked the operating system loader loads the binary into memory. • In .NET: – A .NET compiler takes source code as input and produces MSIL (Microsoft Intermediate Language ) as output instead of a Windows PE.

  7. In C++

  8. The .NET Framework Source code  MSIL machine language using JIT • Common Language Runtime (CLR): Programs are compiled into machine-specific instructions in two steps: • First, the program is compiled into Microsoft Intermediate Language (MSIL) which is placed into the application's executable file. • Using JIT (Just-in-time ) compiler which converts MSIL to machine language, (JIT compile assemblies into native binary that targets a specific platform )

  9. Setting the Path Environment • Assuming that windows and VS.NET2005 is installed on the C drive on your computer, add the following to the Environment Path: – C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727; – C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin; – C:\Program Files\Microsoft Visual Studio 8\VC\bin; – C:\Program Files\Common Files\Microsoft Shared\VSA\8.0\VsaEnv;

  10. Compiling • The .NET Framework can be thought of as a VM (virtual machine) • Save any C# program in a text file “example1.cs”, and set the environment variable PATH to point to csc.exe compiler in the .NET framework directory. • Go to the System Properties by right clicking you My Computer  properties Environment variables click on new type pathC:\WINDOWS\Microsoft.NET\Framework\v2.0.50727. • Now open the command console “cmd” and type “csc example1.cs”.

  11. Exploring the inside of the example1.cs •Intermediate Language Disassembler (ILDASM), can disassemble an assembly and provide the MSIL code. With the MSIL code, a developer can essentially read the application. You can even modify the code as MSIL and reassemble the application. This is called roundtripping. • To see this information, lets disassemble the example1.exe using ILDASM tool provided by the .NET framework. • Go to start Run… and type ildasm. • From the ildasm open the file example1.exe then double click the MANIFIST in the tree view window as shown in the following figure.

  12. Getting Starting, example1.cs • uses the namespace System • entry point must be called Main • output goes to the console • file name and class name need not be identical • Compilation (in the Console window) • csc example1.cs • Execution • example1

  13. Structure of Program in C# •If no namespace is specified => anonymous default namespace •Namespaces may also contain structs, interfaces, delegates and enums

  14. A Program Consisting of 2 Files

  15. Analysis • In C# we define the methods within the class body itself. •Namespaces, are simply a convenient means of semantically grouping elements

  16. Namespaces, keyword • Namespaces are used to logically arrange classes, structs, interfaces, enums and delegates. • The namespaces in C# can be nested. • It is not possible to use any access specifies like private, public etc. with a namespace declarations. The namespaces in C# are implicitly have public access and this is not modifiable. • The .NET framework already contains number of standard namespaces like System

  17. Namespaces • The namespace elements can't be explicitly declared as private or protected • The following code doesn't compile in C#, since the class inside the namespace is declared as private. namespace test{ private class MyClass { }}

  18. Namespace declarations namespace <namespace_name> { <namespace-body> } • You can Nest namespaces: namespace Distrubution { namespace Purchasing { // Define purchasing classes } namespace Receiving { // Define receiving classes } namespace Inventory { // Define inventory classes } }

  19. Nested namespace using System; namespace Outer {namespace Inner { class MyClass { public MyClass() { Console.WriteLine("My Class"); } }} } class MyClient {public static void Main() {Outer.Inner.MyClass mc = new Outer.Inner.MyClass();} }

  20. namespace namespace N1_N2 { class A {} } namespace N3 { using N1_N2; class B: A {} // derived class }

  21. The global namespace has four members: • NamespaceY and NamespaceZ are members. • The classes ClassA and ClassB are also members. • ClassB and ClassC are ambiguous. • ClassB is ambiguous because it is defined twice in the global namespace • ClassC is defined twice in the NamespaceZ namespace.

  22. Namespace • System, is the root namespace • Equally named namespaces in different files constitute a single declaration space.

  23. Namespace

  24. Analysis – cont. • Comments: – //this is a line comment. – /*this is a multi line way of comment*/ – ///XML documentation comments • Every C# application must define a Main method in one of its classes. This method must be defined as public and static. – The static modifier tells the compiler that the Main method is a global method and that the class doesn’t need to be instantiated for the method to be called. – C# provides the usingdirective.

  25. example2.cs

  26. Analysis • Keyword: using • Helps the compiler locate a class that program will use • Identifies pre-defined class • Classes are organized under namespaces

  27. Analysis, cont… • The “using”directive –using System.Console; //error, can’t be done. – Console is a class name. – WriteLine is a static method belongs to Console. • Also you can use aliasing –using output= System.Console • output.WriteLine(“hi”);

  28. C# identifier • C# identifier • Series of characters consisting of letters, digits and underscores ( _ ) • Does not begin with a digit, has no spaces • Examples: Welcome1, identifier, _value, button7 • 7button is invalid • C# is case sensitive (capitalization matters) • a1 and A1 are different

  29. The .NET Type System • In C# every thing is an object. – Most object-oriented languages have two distinct types: • Primitive types or value types (int, char, …) • Types that can be created by users of the language (classes). • All objects (even the ones you create) implicitly derive from a single base class : theSystem.Object type.

  30. System.Object type methods • Public Methods of the System.Object Type – bool Equals Compares two object references at run time todetermine whether they’re the same object. If the two variables referto the same object, the return value is true. With value types, thismethod returns true if the two types are identical and have the samevalue. – string ToString Used by default to retrieve the name of the object. This method can be overridden by derived classes • Protected Methods of the System.Object Type – void Finalize Called by the runtime to allow for cleanup prior to garbage collection.

  31. Types • All types are compatible with object • -can be assigned to variables of type object • -all operations of type object are applicable to them

  32. Value Types versus Reference Types

  33. Simple Types in C#

  34. Compatibility Between Simple Types

  35. The Main Method • Every C# application must define a static method named Main in one of its classes. • You can access the command-line arguments to an application by declaring the Main method as taking a string array type as its only argument. See the following example in the next slide

  36. Example using System; class comnd{ public static void Main(String [] args){ Console.WriteLine("We have {0} args", args.Length); args[0]=args[0]+" do any thing"; foreach (String s in args){ Console.WriteLine("{0}",s); } } }

  37. Expressions:Operators and their Priority Unary + - ~ ! ++x --x Multiplicative * / % Additive + - Shift << >> Relational < > <= >= is as Equality = = != Logical AND & Logical XOR ^ Logical OR | Conditional AND && Conditional OR || Conditional c? x : y Assignment = += -= *= /= %= Operators on the same level are evaluated from left to right

  38. Operators • The C# language has built-in operations for the int, uint, long, ulong, float, double, and decimal types but not for short. – short x, y, z; x=1; y=2; z = x+y; //Error. – But you can do z=(short)(x+y); – C# can’t change the result automatically back to short so you have to do it by your self.

  39. Overflow check • In a checked context, arithmetic overflow raises an exception. • In an unchecked context, arithmetic overflow is ignored and the result is truncated. try{ checked { short f = 321; byte g = (byte)f; Console.WriteLine("(byte)321 = {0}", g); } } catch (Exception z) { Console.WriteLine("{0}", z.Message); }

  40. Overflow check • Overflow is not checked by default int x = 1000000; x = x * x; // -727379968, no error • Overflow check can be turned on x = checked (x * x); // System.OverflowException checked{ ... x = x * x; // System.OverflowException ... }

  41. typeof and sizeof • typeof: Returns the Type descriptor for a given type (The type descriptor of an object o can be retrieved with o.GetType()) Object o=new object(); Type t= o.GetType(); Console.WriteLine(t.Name); // Object Type t = typeof (int); Console.WriteLine (t.Name); // Int32 • Sizeof: Returns the size of a type in bytes Console.WriteLine(sizeof(int)); // 4 byte

  42. Declaration

  43. Blocks

  44. Declaration of Local Variables

  45. If-statement, Wrong…. int foo=1; if (foo) { Console.WriteLine("yes"); } // ERROR: attempting to convert int to bool

  46. if Statement char ch=‘*’; int val ; if('0' <= ch && ch <= '9') val = ch -'0'; else if('A' <= ch && ch <= 'Z') val = 10 + ch -'A'; else{ val = 0; Console.WriteLine("invalid character {0}", ch); }

  47. switch Statement • Type of switch expressionnumeric, char, enum or string(null ok as a case label). Type of switch expression: numeric, char, enum or string (null ok as a case label).

More Related