850 likes | 871 Views
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.
E N D
Lecture1Introduction to C# Instructor: Haya Sammaneh
Features of C# Very similar to Java 70% java, 10% C++, 5% Visual Basic, 15% new
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
.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.
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 )
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;
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 pathC:\WINDOWS\Microsoft.NET\Framework\v2.0.50727. • Now open the command console “cmd” and type “csc example1.cs”.
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.
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
Structure of Program in C# •If no namespace is specified => anonymous default namespace •Namespaces may also contain structs, interfaces, delegates and enums
Analysis • In C# we define the methods within the class body itself. •Namespaces, are simply a convenient means of semantically grouping elements
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
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 { }}
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 } }
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();} }
namespace namespace N1_N2 { class A {} } namespace N3 { using N1_N2; class B: A {} // derived class }
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.
Namespace • System, is the root namespace • Equally named namespaces in different files constitute a single declaration space.
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.
Analysis • Keyword: using • Helps the compiler locate a class that program will use • Identifies pre-defined class • Classes are organized under namespaces
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”);
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
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.
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.
Types • All types are compatible with object • -can be assigned to variables of type object • -all operations of type object are applicable to them
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
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); } } }
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
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.
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); }
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 ... }
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
If-statement, Wrong…. int foo=1; if (foo) { Console.WriteLine("yes"); } // ERROR: attempting to convert int to bool
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); }
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).