C#
C#
Why .NET?
Web Services. Security. Built in Server side Controls. Optimized User Interface. (Browser Type & versions) Improved performance. Built in Classes. .asx templates to standardize page layouts. Ease in integration of other MS products.
Luminus IT Education 2
.NET Framework
Luminus IT Education
Luminus IT Education
Introduction to C#
C# is a new generation language designed to work within the .NET framework. Strongly typed, object-oriented language that is a direct descendent of other languages including C, C++, and Java. C# was developed by a Anders Hejlsberg. The C# language is highly expressive in implementing all the features of a modern object-oriented programming language, It provides support for encapsulation, inheritance, and polymorphism. C# has about 80 keywords and a dozen built-in data types.
Luminus IT Education 5
Cont..
C# includes language features such as single inheritance, multiple interfaces, and compilation to an intermediate format. There are some C# features that exist primarily to work within the .NET Framework, and it could even be argued that some features of .NET exist because of C#. C# features, such as versioning, COM support, and Multilanguage development, which cant be found in Java. Following is a list of features that C# and Java share in common, which are intended to improve on C++.
Luminus IT Education
Cont..
Both languages compile to an intermediate format that is run in a managed environment. Each runtime environment provides support for automatic garbage collection. All classes in both languages descend from Object and are allocated on the heap when they are created. Everything must belong to a class, which means that there are no global functions or constants. Both languages abandoned multiple inheritances, although implementing multiple interfaces is allowed. Both C# and Java use exceptions for error handling. Arrays are bound checked. Inline code comments are used to produce API documentation. They both use packages/namespaces to avoid type collision.
Luminus IT Education 7
Cont..
In C# all methods start with a capital letter C# has Object.Equals(), whereas Java has object.equals(). C# has Object.Finalize(), whereas Java has Object.finalize(). C# has Object.ToString(), whereas Java has Object.toString().
Luminus IT Education
Luminus IT Education
Getting Started.
To make sure that the SDK has been installed properly open a command line window (cmd.exe) and type csc.exe /help on the command prompt. If the program has been installed properly, you should see something similar to Figure
Luminus IT Education
10
Cont..
The csc.exe program is the main C# compiler for the .NET SDK. It has several switches that allow you to specify compiler options. By typing /help, the program will list all the different compiler options available as shown in above picture.
Luminus IT Education
11
Luminus IT Education
12
Luminus IT Education
13
Cont..
All C# programs are JIT compiled, unlike Java where it is interpreted at most times by a Java runtime. Therefore, after compiling the program, all you have to do is type the output filename at the command prompt to execute it.
Output I wrote my first C# program at: 5/14/2002 2:24:37 PM
Luminus IT Education 14
Cont..
If you execute this same program with some arguments an error dialogue box will pop up similar to Figure
Runtime Error Dialogue Box Just click on Cancel and you should see the following
Luminus IT Education
15
Cont..
C:\test>Hello Praveen Kumar I wrote my first C# program at: 5/15/2002 2:27:01 AM Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array. at Hello.Main(String[] args)
Luminus IT Education
16
Cont..
The error message doesnt really tell us where the problem is. To solve this, we can recompile the Hello.cs with the /debug switch. csc /debug Hello.cs By adding this debug switch the compiler will generate an extra file with the .pdb extension, which contains debugging information. After running the program again, it should display more information, as shown:
Luminus IT Education 17
Cont..
C:\test>Hello Praveen Kumar I wrote my first C# program at: 5/15/2002 2:48:33 AM Unhandled Exception: System.IndexOutOfRangeException:Index was outside the bounds of the array. at Hello.Main(String[] args) in C:\test\Hello.cs:line 17
Luminus IT Education
18
Luminus IT Education
19
Cont..
1. In Explorer, launch the debugger, which can be found in <InstalledDirectory>/Microsoft.NET/FrameworkSDK/Gui Debug/dbgclr.exe. Click on Debug | Program To Debug. This will let you specify the program you wish to debug and enter in any arguments the program needs. You can enter Hello.exe under Program, and type some names under the Arguments field. After doing so, you should see something similar to Figure
2.
Luminus IT Education
20
Cont..
3. Click on OK. Once thats done, you can start debugging the program by clicking on Debug | Start F5, or by simply pressing the F5 key. This will start the debugging process and the program will halt once it encounters an error. Click on Break.The program will pause and highlight the piece of code that caused the error. We can visibly see where the problem is occurring. Now we can set a breakpoint at this location in the code so that we can watch whats causing it.To do this, rightclick on the line and select InsertBreakpoint from the menu
4. 5.
Luminus IT Education
21
Cont..
6. Now we can start the debugging process again, and as soon as the debugger encounters the breakpoint it will automatically stop the program. The debugger provides the Locals window to display all the values of all the local variables. This is extremely useful because you get a glimpse of the variable states at a specific time of code execution. This is the key in analyzing and solving the bug. Output C:\test>Hello Praveen Kumar I wrote my first C# program at: 5/15/2002 4:24:11 AM You wanted to say hello to Praveen Kumar
Luminus IT Education
22
Luminus IT Education
23
Luminus IT Education
24
Cont..
As a modern abstraction, classes reduce complexity by: Hiding away details (implementation), Highlighting essential behavior (interface), and Separating interface from implementation.
Luminus IT Education
25
Declaring Classes
As mentioned previously, a class declaration encapsulates two kinds of class members: Data, otherwise known as a field, attribute, or variable, and Behavior, otherwise known as a method, operation, or service. In below Ex. fields and methods are used to represent the data and behavior members of a class. Consider the ID class given below. This class defines an abstraction that represents a personal identification and is composed of two fields and four methods. The two fields, firstName and lastName, are both of type string; the four methods simply retrieve and set the values of the two data fields.
Luminus IT Education 26
Cont..
class ID { // Methods (behavior) string GetFirstName() { return firstName; } string GetLastName() { return lastName; } void SetFirstName(string value) { firstName = value; } void SetLastName(string value) { lastName = value; }
// Fields (data) string firstName = Praveen"; string lastName = Kumar"; }
Luminus IT Education 27
Creating Objects
An instantiation is the creation or construction of an object based on a class declaration. This process involves two steps. First, a variable is declared in order to hold a reference to an object of a particular class. In the following example, a reference called id is declared for the class Id: ID id; Once a variable is declared, an instance of the class is explicitly created using the new operator. This operator returns a reference to an object where upon it is assigned to the reference variable. As shown here, an object of the ID class is created and a reference to that object is assigned to id:
Luminus IT Education 28
Cont..
id = new ID(); The previous two steps, declaring a variable and creating an object, can also be coalesced into a single line of code: ID id = new ID();
Luminus IT Education
29
Access Modifiers
To uphold the principle of information hiding, access to classes and class members may be controlled using modifiers that prefix the class name, method, or data field. In this section, we first examine those modifiers that control access to classes, followed by a discussion on the modifiers that control access to methods and data fields.
Luminus IT Education
30
Cont..
internal class ID { ... } Classes are, by default, internal; therefore, the internal modifier is optional.
Luminus IT Education
32
Cont..
Internal methods and data fields are only visible among classes that are part of the same compiled unit. Methods or data fields that are protected internal have the combined visibility of internal and protected members. By default, if no modifier is specified for a method or data field then accessibility is private. If a class is internal, then access modifiers is similar to those of a public class except for one key restriction: Access is limited to those classes within the same compiled unit. Otherwise, no method or data field of an internal class is directly accessible among classes that are compiled separately.
Luminus IT Education
34
Cont..
When used in conjunction with the data fields and methods of a class, access modifiers dually support the notions of information hiding and encapsulation. By making data fields private, data contained in an object is hidden from other objects in the system. Hence, data integrity is preserved. By making methods as private, access and modification to data is controlled via the methods of the class. Hence, no direct external access by other objects ensures that data behavior is also preserved.
Luminus IT Education
35
Access Modifiers
Luminus IT Education
36
Tip
As a rule of thumb, good class design declares data fields as private and methods as public. It is also suggested that methods to retrieve data members (called getters) and methods to change data members (called setters) be public and protected, respectively.
Luminus IT Education
37
Namespaces
A namespace is a mechanism used to organize classes (even namespaces) into groups and to control the proliferation of names. This control is absolutely necessary to avoid any future name conflicts with the integration (or reuse) of other classes that may be included in an application. If a class is not explicitly included in a namespace, then it is placed into the default namespace, otherwise known as the global namespace
Luminus IT Education
38
Declaring Namespaces
The following example presents a namespace declaration for the Presentation subsystem that includes two public classes, Ex. namespace Presentation { public class First { ... } public class Second { ... } }
Luminus IT Education
39
Cont..
This Presentation namespace can also be nested into a Project namespace containing all three distinct subsystems as shown here: Ex.
namespace Project { namespace Presentation { public class First { ... } public class Second{ ... } } namespace Business { // Domain classes ... } }
Luminus IT Education 40
Cont..
Access to classes and nested namespaces is made via a qualified identifier. For example, Project.Presentation provides an access path to the classes First and Second. This mechanism allows two or more namespaces to contain classes of the same name without any conflict. Have a look at the below example.
Luminus IT Education
41
Cont..
namespace Compilers { namespace C { class Lexer { ... } class Parser { ... } } namespace Csharp { class Lexer { ... } class Parser { ... } } }
Luminus IT Education 42
Cont..
A graphical representation of these qualifications.
Luminus IT Education
43
Importing Namespaces
The using directive allows one namespace to access the types (classes) of another without specifying their full qualification. UsingDirective = "using" ( UsingAliasDirective | | amespaceName ) "; For example, the WriteLine method may be invoked using its full qualification, System.Console.WriteLine. With the using directive, we can specify the use of the System namespace to access the WriteLine method via its class Console:
Luminus IT Education 44
Cont..
Ex. using System; public class Welcome { public static void Main() { Console.WriteLine( Practical guide for C#! "); } }
Luminus IT Education 45
Luminus IT Education
46
Cont..
ParserCompilationUnit.cs file (Part 1): public partial class Parser { private ILexer lexer; private IReportable errorReporter; private ISymbolTable symbolTable; // ... // Compilation Unit productions void ParseCompilationUnit() { ... } void ParseNamespace() { ... } // ... }
Luminus IT Education 47
Cont..
ParserClass.cs file (Part 2): public partial class Parser { // Class productions void ParseClassDecl() { ... } void ParseClassMemberDecl() { ... } // ... }
Luminus IT Education
48
Cont..
ParserExpr.cs file (Part 3): public partial class Parser { // Expression productions void ParseExpr() { ... } void ParseExprList() { ... } // ... } When all the 3 files are compiled together, the resulting code is the same as if the class had been written as a single source file Parser.cs:
Luminus IT Education
49
Cont..
public class Parser { private ILexer lexer; private IReportable errorReporter; private ISymbolTable symbolTable; // ... // Compilation Unit productions void ParseCompilationUnit() { ... } void ParseNamespace() { ... } // ... // Class productions void ParseClassDecl() { ... } void ParseClassMemberDecl() { ... } // ... // Expression productions void ParseExpr() { ... } void ParseExprList() { ... } // ... }
Luminus IT Education
50
Luminus IT Education
51
Luminus IT Education
52
Cont..
Luminus IT Education
53
Cont..
In C#, all data types are part of the System namespace and can be referenced. For ex, the bool data type can be referenced as System.Boolean. C# supports two kinds of types, value types and reference types. Value types hold actual data in the form of variables. They are stored in the stack by C#, which is a temporary memory space. With value types, every stored value is stored separately from all of the other stored values, and changing one will not affect another Reference types hold objects, which refer to actual data. Since an object can be referred to by multiple variables, operations using one of the variables can affect operations by the other
Luminus IT Education 54
Cont..
class Program { static void Main(string[] args) { int i = 10; //Boxing object obj = i; // unboxing int j = Convert.ToInt32(obj); Console.WriteLine("(Boxing) obj=" + obj); Console.WriteLine("(Unboxing) j =" + j); Console.Read(); } }
Luminus IT Education
55
Variables
C# works with variables in a manner similar to Java. All variables must be declared prior to use and are declared with a statement of what data type the variable is. Variables can be initialized with a default value when declared and multiple variables of the same type can be declared at the same time. There are three main types of variables: class variables, instance variables, and local variables. Class variables are prefaced with the term static and are initialized only once, when the class is initialized.
Luminus IT Education
56
Cont..
Instance variables are initialized every time an instance of the class is created. The last variable type is local, and these are initialized every time the variable is declared. Ex, class SetVars { public static int a = 10; // Class variable public int b = 4; //Instance Variable }
Luminus IT Education
57
Cont..
class WorkVars { static void Main() { int c; // local variable SetVars MyVars = new SetVars(); SetVars MyOtherVars = new SetVars(); } }
Luminus IT Education
58
Constants
Constants in C# are basically variables that are readonly. In C#, a constant is declared by using the keyword const prior to the data type in your declaration. By specifying a variable as a constant, you can be sure that the value of the variable will not be changed from its original assignment. Ex,
class SetVars { public static int a; public int b; public const string IniFileName = "SETVARS.INI"; }
Luminus IT Education 59
Assignment Statements
When assigning values to variables, we use the = symbol to show that the variable should be set to whatever follows the = symbol. Ex, class BoxTest { static void Main() { int Length = 10, Width = 5; int Height; Height = 2; } }
Luminus IT Education 60
Luminus IT Education
61
Cont..
Ex, using System; class ImplicitConversion { public static void Main() { byte a=1; int b=1234; int c=b; //Implicit cast double d= b; //Explicit Console.WriteLine("{0}", c); Console.WriteLine("{0}", d); } }
Luminus IT Education 62
Cont..
Explicit conversions will attempt to convert the value stored in your source variable into the data type of your destination variable. Note: Not all conversions will be successful. Some data may be lost in the conversion. This may be in the form of truncated data following a decimal point, or modified numeric values.
Luminus IT Education
63
Cont..
Ex, using System; class ExplicitConv { static void Main() { double a = 5.654321; int b; b = (int) a; Console.WriteLine("The value is {0}", b); } }
Luminus IT Education 64
Operators
C#, much like Java, makes available a large number of operators for us to use. In C#, these are broken up into six major groups: mathematical, assignment, increment and decrement, relational, logical, and bitwise.
Luminus IT Education
65
Mathematical Operators
In C#, mathematical operators perform in the same way as arithmetic operators do in Java.
Luminus IT Education
66
Cont..
Ex, using System; class Operators { static void Main() { int a = 5, b = 10, c = 15; int d = a + b; int e = c - b; int f = a * e; int g = f / a; Console.WriteLine("{0}", g); Console.WriteLine("{0}", g % 2); } }
Luminus IT Education 67
Assignment Operators
Luminus IT Education
68
Cont..
Ex, class Operators { static void Main() { int a, b, c, d, e; a = 14; b = 15; c = 20; d = a + b - c; //d=9 c += d; //c=29 e = c + d; //e=38 e /= 2; //e=19 Console.WriteLine("{0}", e);
}
}
Luminus IT Education 69
Luminus IT Education
70
Cont
Ex, class Operators { static void Main() { int a=10, b, c; b = a++; //Postfix operation c = ++a; //Prefix operation Console.WriteLine("{0}", b); Console.WriteLine("{0}", c); b = b--; //Postfix operation c = --c; //Prefix operation Console.WriteLine("{0}", b); Console.WriteLine("{0}", c); } }
Luminus IT Education 71
Relational Operators
Relational operators basically take two values and evaluate the relationship between them.
Luminus IT Education
72
Cont
Ex, using System; class Operators { static void Main() { bool a = 4 > 5; Console.WriteLine("{0}", a); } }
Luminus IT Education
73
Luminus IT Education
74
Programming Structures
Branch Statements
Branch statements, also known as Conditional statements, permit us to branch our code in a different direction based on a condition.
Cont..
Ex, class Program { static void Main(string[] args) { int x = 10; if (x == 10) { Console.WriteLine("X is equal to 10"); } else { Console.WriteLine("X is not equal to 10"); } } }
Luminus IT Education 76
Cont..
class Program { static void Main(string[] args) { int x = 1; int y = 2; if (x == 1) if (y == 2) System.Console.WriteLine("x = 1, y = 2"); else System.Console.WriteLine("x = 1, y != 2"); else System.Console.WriteLine("x != 1"); } }
Nested If/Else
Luminus IT Education
77
Luminus IT Education
78
Cont..
Ex, class Program { static void Main(string[] args) { String testString = "Test"; switch (testString) { case "Hello": System.Console.WriteLine("The string says Hello."); break; case "Test": System.Console.WriteLine("The string says Test"); break; default: System.Console.WriteLine("The string is unknown"); break; } } }
Luminus IT Education 79
While Loop
The while loop executes a segment of code 0 or more times, based on the outcome of a boolean control expression. The while loop is called an indeterminate loop and is usually used when the program will be unaware of the number of iterations of the loop until it has been entered.
Luminus IT Education
80
Cont..
Ex, class Program { static void Main(string[] args) { bool noMoreRecords = false; while (!noMoreRecords) { Console.WriteLine("Inside While Loop"); Console.Read(); } } }
Luminus IT Education
81
Luminus IT Education
82
Luminus IT Education
83
Ex,
class Program { static void Main(string[] args) { int x = 4; goto Print; Console.WriteLine("Test"); // This line will be skipped x = 5; // This line will be skipped Print: Console.WriteLine(x); Console.Read(); } }
Luminus IT Education
84
Luminus IT Education
86
Cont..
Ex, class Program { static void Main(string[] args) { Console.WriteLine("Main Line 1"); MethodSample(); Console.WriteLine("Main Line 2"); Console.Read(); } static void MethodSample() { Console.WriteLine("MethodSample line 1"); return; } }
Luminus IT Education 87
Arrays
An array is a series of objects consisting of the same data types. Individual objects in the series, called elements, are referenced by their index into the array.
int[] IntegerArray;
Luminus IT Education 89
Cont..
The most common way is by using the new operator, which will initialize an array, but not assign any values to it. The following code will create an integer array with four elements: int[] IntegerArray = new int[4]; If you knew the values you wished to assign the array elements at the time you created the array, you can also use the following syntax. int[] integerArray = {1,2,3,4};
Luminus IT Education 90
Cont..
To access an individual element of an array you specify the index of that element. IntegerArray[1].ToString();
Luminus IT Education
91
Collections.
ArrayList - The classic problem with the Array type is its fixed size. If you do not know in advance how many objects an array will hold, you run the risk of declaring either too small an array (and running out of room) or too large an array (and wasting memory). - Your program might be asking the user for input, or gathering input from a web site. As it finds objects (strings, books, values, etc.), you will add them to the array, but you have no idea how many objects you'll collect in any given session. The classic fixed-size array is not a good choice, as you can't predict how large an array you'll need.
Luminus IT Education 92
Cont..
The ArrayList class is an array whose size is dynamically increased as required.
class Program { static void Main(string[] args) { ArrayList ObjAL = new ArrayList(); for (int i = 1; i <= 10; i++) { ObjAL.Add(i); } foreach (int x in ObjAL) { Console.WriteLine(x + " "); } Console.Read(); } }
Luminus IT Education 93
Hashtable
A hashtable is a dictionary optimized for fast retrieval.
using System.Collections; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Hashtable Ht = new Hashtable(); Ht.Add("ID", "1"); Ht.Add("Name", "Praveen"); Console.WriteLine("ID : " + Ht["ID"]); Console.WriteLine("NAME : " + Ht["Name"]); Console.Read(); } } }
Luminus IT Education 94
Exceptions
Exception handling permits you to execute code and handle error conditions prior to the program exiting. In C# exception handling requires three code blocks: try, catch, and finally. Catching Exceptions To catch an exception you would execute the code you want to execute in a try block, and follow this block with a catch block. The code in which the exception is likely to occur must be encased in a try block followed by a catch block
Luminus IT Education
95
Cont..
Typically you would end with a finally block to perform any cleanup code that must occur regardless if an exception was thrown or not. Ex,
Luminus IT Education
96
Cont..
static void Main(string[] args) { try { Console.WriteLine("Enter the number to print Multiplication Chart:"); int a = Convert.ToInt32(Console.ReadLine()); int b; for (int i = 1; i <= 10; i++) { b = a * i; Console.WriteLine(a + " x " + i + " = " + b); } Console.Read(); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.Read(); } finally { // Clean Up activities. } } } Luminus IT Education
97
Throwing Exceptions
Exceptions are not just thrown by the Framework libraries. In fact, you can, and should, throw exceptions yourself if the situation requires.
Luminus IT Education
98
Luminus IT Education
99
Cont..
class Program { static void Main(string[] args) { try { int a = Convert.ToInt32(Console.ReadLine()); int b = Convert.ToInt32(Console.ReadLine()); if (b == 0) { throw new FormatException("My Message- Invalid values"); } else { int c = a / b; Console.WriteLine("Result:"+c.ToString()); Console.Read(); } } catch (FormatException ex) { Console.WriteLine("----- We caught FormatException -----"); Console.WriteLine(ex.Message.ToString()); Console.Read(); } Luminus IT Education } }
100
Cont..
Luminus IT Education
101
Luminus IT Education
102
Cont..
// C# base class public class Employee { protected string name ; protected string ssn ; }
Luminus IT Education
103
Cont..
// C# derived class public class Salaried : Employee { protected double salary ; public Salaried(string name, string ssn, double salary) { this.name = name ; this.ssn = ssn ; this.salary = salary ; } } Salaried s = new Salaried( "Albert","123456", 800.00 ) ;
Luminus IT Education 104
Luminus IT Education
105
Cont..
// C# base class public class Employee { protected string name ; protected string ssn ; public Employee(string name, string ssn) { System.Console.WriteLine("Employee") ; this.name = name ; this.ssn = ssn ; } }
Luminus IT Education 106
Cont..
// C# derived class public class Salaried : Employee { protected double salary ; public Salaried(string name, string ssn, double salary) : base(name, ssn) { System.Console.WriteLine("Salaried") ; this.salary = salary ; } }
Luminus IT Education
107
Cont..
public class Test { static void Main() { new Salaried("Albert","123456",80000.00 ) ; } } Output: Employee Salaried
Luminus IT Education
108
Polymorphism
Polymorphism comes from two Greek root words:poly means many and morphe means form. The idea is that something may take on many forms. If we apply our definition of polymorphism we see that the Employee class takes on four specialized forms (Salaried, Commissioned, Hourly, and TruckDriver). It is quite common that we will use base class references to refer to derived class objects.
Luminus IT Education
109
Cont..
Ex, Employee [] employees = new Employee[4] ; employees[0] = new Salaried("Becky","123456789",80000) ; employees[1] = new Commissioned("Chuck","234567891",20000,.05) ; employees[2] = new Hourly("Deb","345678912",19.75) ; employees[3] = new TruckDriver("Earl","456789123",20000,0.30) ;
Luminus IT Education 110
Cont..
If you look closely you see that although we created all of these different kinds of objects, we created only one kind of reference to access them - employee references.
Luminus IT Education
111
Abstract Classes
// C# abstract class public abstract class Employee {
protected string name ; protected string ssn ; protected Employee(string name, string ssn)
Luminus IT Education
112