C# by Zaheer Abbas Aghani
Upcoming SlideShare
Loading in...5
×
 

C# by Zaheer Abbas Aghani

on

  • 2,378 views

 

Statistics

Views

Total Views
2,378
Views on SlideShare
2,378
Embed Views
0

Actions

Likes
1
Downloads
96
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft Word

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

C# by Zaheer Abbas Aghani C# by Zaheer Abbas Aghani Document Transcript

  • Introduction to C# • C# is a language that was created by Microsoft and submitted to ECMA for standardization. • Its creators were a team of people at Microsoft that included the guidance of Anders Hejlsberg. • Hejlsberg is a Microsoft Distinguished Engineer who has created other products and languages, including Borland Turbo C++ and Borland Delphi. • With C#, he and the team at Microsoft focused on using what was right about existing languages and adding improvements to make something better. • Although C# was created by Microsoft, it is not limited to just Microsoft platforms. • C# is a powerful and flexible programming language. Like all programming languages, it can be used to create a variety of applications.Execution of a C# Program1. Compilation - Converting source code in C#language into bytecode in IL (IntermediateLanguage) using C# compiler.This step is usually done by the Microsoft C#compiler like the "csc" command line tool, whichwill actually write the bytecode in a PE (PortableExecutable) file.2. Execution - Converting bytecode inIntermediate Language into native code inmachine language on-the-fly (or just-in-time) andexecuting the native code in a single step.This step is usually done by the Microsoft CLR(Common Language Runtime), which will beinvoked when a PE file with IL bytecode is loadedinto the Windows system.
  • Steps involve in C# program DevelopmentObject Oriented Programming • Object Oriented Programming is a technique for system modeling. OOP may be considered as collection of interacting objects. Each object is capable of sending and receiving messages and processing data.Key Concepts of Object Orientation 1. Classes and Object 2. Abstraction 3. Encapsulation 4. Polymorphism 5. Inheritance 1. Classes and Objects:Class: • Class is a blueprint or template for object. • Class defines the characteristics of an object Characteristics include:
  • • Attributes (Field or properties) • Behaviors (method or operation) Eg of Class are. Teacher, Student, CarIn an OO model, some of the objects exhibit identical characteristics (properties andbehaviour) We say that they belong to the same class. Class : Car Attributes: year, make, model, color, number of doors, engine Behavior: on, off, changeGears, accelerate, decelerate, turn, and brakeObject: • An object is instance of class • Creating an object is also known as instantiation. An object is a self-contained piece of functionality that can be easily used, and re-used as the building blocks for a software application. Objects consist of data variables and functions (called methods) that can be accessed and called on the object to perform tasks. These are collectively referred to as members. 2. Abstraction • Abstraction is a way to cope with complexity. • Principle of abstraction:“Capture only those details about an object that are relevant to current perspective”Example:Ali is a PhD student and also teaches BS studentsAttributes • Name • Student Roll No • Designation • Salary • Year of Study • Employee ID • CGPA • AgeBehavior
  • • Study • TakeExam • GiveExam • DevelopExam • PlaySports • DeliverLecture • Eat • WalkIf we see from Student’s Perspective; only following information is requiredAttributes • Name • Student Roll No • Year of Study • CGPABehavior • Study • GiveExam • PlaySportsIf we see from Teacher’s Perspective; only following information is requiredAttributes • Designation • Salary • Employee ID • AgeBehavior • TakeExam • DevelopExam • DeliverLecture 3. Encapsulation • Data and behavior are tightly coupled inside an object
  • • Both the information structure and implementation details of its operations are hidden from the outer world• Objects encapsulate data and the procedures for manipulating that data. In a sense, the object hides the details of the implementation from the user of that object. Example A Phone stores phone numbers in digital format and knows how to convert it into human-readable characters We don’t know• How the data is stored• How it is converted to human-readable characters Advantage• Simplicity and clarity• Low complexity• Better understanding• security no one can change it4. Polymorphism• In general, polymorphism refers to existence of different forms of a single entity• it is the ability of one type to appear as , and be used like another type• polymorphism means that different objects can behave in different ways for the same message (stimulus) Example - Coure and Carola belog to Car class; but Coure car brake at 33 feet per sec And carola car brake at 29 feet per sec - Both Diamond and Coal are different forms of Carbon5. Inheritance• A subclass is specified version of a class, which inherits attributes and behavior from the parent class• Besides inherited characteristics, a child may have its own unique characteristics
  • Inheritance enables you to create a new class that reuses, extends, and modifies the behavior thatis defined in another class. The class whose members are inherited is called the base class, and theclass that inherits those members is called the derived class.In C# multiple Inheritance is not allowed; but it can be possible by using interfaces. However MultiLevel inheritance is allowed.Object-Orientation – Advantages • People think in terms of objects • OO models map to reality • Therefore, OO models are – easy to develop – easy to understandClassesDefining a ClassTo keep things simple, a keyword called class is used to define classes. The basic structure of aclass follows this format:class identifier{class-body ;}identifier is the name given to the class, and class-body is the code that makes up the class. Nameshould be meaningful.Declaring ClassesAfter a class is defined, you use it to create objects. A class is just a definition used to createobjects. A class by itself does not have the capability to hold information or actually performroutines. Instead, a class is used to declare objects. The object can then be used to hold the dataand perform the routines as defined by the class.The declaration of an object is commonly referred to as instantiation. Or an object is an instance ofa class.The format of declaring an object from a class is as follows:class_name object_identifier = new class_name();
  • class_name is the name of the class, and object_identifier is the name of the object beingdeclared.The new keyword indicates that a new instance is to be created.Remember, a class is only a definition: It doesn’t store anything. The object needs to storeinformation, so it needs memory reserved. The new keyword reserves the memory.The Members of a ClassMember of class can be data members or function/method members. Data members includevariables and constants. Function members are routines that perform an action.The other type of element that is part of a class’s body is function members.Member DescriptionConstants Constant values associated with the classFields/Variables A field is a variable that is associated with a class or with an instance of a class.Methods Computations and actions that can be performed by the classIndexers Actions associated with indexing instances of the class like an arrayOperators Conversions and expression operators supported by the classConstructors Actions required to initialize instances of the class or the class itselfDestructors Actions to perform before instances of the class are permanently discardedAccessing Data MembersWhen you have data members declared, you want to get to their values. To access a datamember, you use both the name of the object and the data member. The member operator,which is a period (.) separates these.class Point{public int x;public int y;}class pointApp{public static void Main(){Point starting = new Point();Point ending = new Point();starting.x = 1;starting.y = 4;ending.x = 10;ending.y = 11;
  • System.Console.WriteLine(“Point 1: ({0},{1})”,starting.x, starting.y);System.Console.WriteLine(“Point 2: ({0},{1})”,ending.x, ending.y);}}ConstructorsA constructor looks very much like a method, but with no return type and a name which is thesame as the name of the class. When an object is first created its constructor is created in thememory. If user does not create constructor of the class the default constructor will beautomatically called. Constructors are not inherited.Example:public class MySimpleClass{ public MySimpleClass () // Default Constructor { Console.WriteLine (“This is Default Constructor”); }}Two types of constructors exist: instance constructors, used when each instance or object iscreated, and static constructors, called before any objects are created for a class.Instance ConstructorsAn instance constructor is a method that is automatically called whenever an object isinstantiated. This constructor can contain any type of code that a normal method can contain.Static ConstructorsAs with data members and methods, you can also create static constructors. A constructordeclared with the static modifier is called before the first object is created. It is called only onceand then is never used again. Only static members are allowed in the static constructor.using System;class Cons { public static int a; public int b; // static constructor static Cons(){ a = 99; Console.WriteLine("Inside static constructor.");
  • } // instance constructor public Cons(){ b = 100; Console.WriteLine("Inside instance constructor."); }}class MainClass{ public static void Main(){ Cons ob = new Cons(); Console.WriteLine("Cons.a: " + Cons.a); Console.WriteLine("ob.b: " + ob.b);}}Constructor Overloading:C# supports overloading of constructors that means we can have constructors with different set ofparameters.using System;public class mySampleClass{ public mySampleClass(){ Console.WriteLine("This is Defualt Constructor");} public mySampleClass(int a, int b) { int val1= a; int val2= b; Console.WriteLine("This is constructor with two values,Value1={0} and Value2={1} and Its Sum is: {2}", val1, val2,val1+val2); } public mySampleClass(int Age, string Name) { //Age = 20; //Name = "ALI"; Console.WriteLine("Age={0} and Name={1}", Age, Name); }
  • }class Testing{ static void Main() { int num1, num2; mySampleClass obj = new mySampleClass(); Console.WriteLine("Insert Any Two Values"); num1 = int.Parse(Console.ReadLine()); num2 = int.Parse(Console.ReadLine()); mySampleClass obj1 = new mySampleClass(num1, num2); mySampleClass obj2 = new mySampleClass(20, "ALI"); }}Basics of C# Sharp: 1. Variables:A variable is a named data storage location in your computer’s memory. By using a variable’sname in your program, you are, in effect, referring to the information stored there.Naming Your VariablesTo use variables in your C# programs, you must know how to create variable names. In C#,variable names must adhere to the following rules:• The name can contain letters, digits, and the underscore character (_).• The first character of the name must be a letter. The underscore is also a legal first character,but its use is not recommended at the beginning of a name. An underscore is often used withspecial commands. Additionally, it is sometimes hard to read.• Case matters (that is, upper- and lowercase letters). C# is case sensitive; thus, the names countand Count refer to two different variables.• C# keywords can’t be used as variable names. Recall that a keyword is a word that is part of theC# language. 2. Type Casting
  • • Type casting is the process by which we can convert variable of one data type to another data type.Casting can be done in to two ways; • Implicit casting • Explicit castingExamplestatic void TestCasting(){ int i = 10; float f = 0; f = i; // An implicit conversion, f = 0.5F; i = (int)f; // An explicit conversion.}Data Loss • In implicit conversion no data will be lost • In explicit conversion some data will be lost 3. Boxing and Unboxing • Everything is object in C#; That is not exactly true; however, everything can be treated as an object. • Boxing is the conversion of a value type to a reference type (object). Unboxing is the explicit conversion of a reference type to a value type. A value that is unboxed must be put into a data type equivalent to the data stored. • Unboxing requires that that you explicitly convert an object to a value type. This can be done using a cast. • Boxing The assignment
  • object obj = 3; wraps up the value 3 into a heap object int i = 123; object o = (object)i; // boxing• Unboxing The assignment int x = (int) obj; unwraps the value again o = 123; i = (int)o; // unboxing Example: using System; class myApp { static void Main() { float val = 3.14F; // Assign a value type a value object boxed = val; // boxing val into boxed float unboxed = (float) boxed; // unboxing boxed into unboxed
  • Console.WriteLine(“val: {0}”, val); Console.WriteLine(“boxed: {0}”, boxed); Console.WriteLine(“unboxed: {0}”, unboxed); }} 4. Data TypesThere are two main types of data types 1. Primitive data types 2. Reference data types 1. Primitive data typesNumeric Variable TypesC# provides several different types of numeric variables. You need different types of variablesbecause different numeric values have varying memory storage requirements and differ in the easewith which certain mathematical operations can be performed on them.The following are the basic sections break the different numeric data types into four categories: • Integral • Floating point • Decimal • Boolean • EnumerationThe Integral Data TypesIntegral data types store integers. Recall that an integer is basically any numeric value that does notinclude a decimal or a fractional value. The numbers 1, 1,000, 56,000,000,000,000, and -534 areintegral values.C# provides nine integral data types, including the following: • Integers (int and uint) • Shorts (short and ushort) • Longs (long and ulong)
  • • Bytes (byte and sbyte) • Characters (char)Example1 using System; class Chars { public static void Main() { int ctr; char ch; for( ctr = 63; ctr <= 94; ctr = ctr + 1) { ch = (char) ctr; Console.WriteLine( “{0} is {1}”, ctr, ch); } } } Example2:using System; class Sizes{public static void Main()Console.WriteLine( “nA byte is {0} byte(s)”, sizeof( byte ));Console.WriteLine( “A sbyte is {0} byte(s)”, sizeof( sbyte ));Console.WriteLine( “A char is {0} byte(s)”, sizeof( char ));Console.WriteLine( “nA short is {0} byte(s)”, sizeof( short ));Console.WriteLine( “An ushort is {0} byte(s)”, sizeof( ushort ));Console.WriteLine( “nAn int is {0} byte(s)”, sizeof( int ));Console.WriteLine( “An uint is {0} byte(s)”, sizeof( uint ));Console.WriteLine( “nA long is {0} byte(s)”, sizeof( long ));
  • Console.WriteLine( “An ulong is {0} byte(s)”, sizeof( ulong ));Console.WriteLine( “nA float is {0} byte(s)”, sizeof( float ));Console.WriteLine( “A double is {0} byte(s)”, sizeof( double ));Console.WriteLine( “nA decimal is {0} byte(s)”, sizeof( decimal));Console.WriteLine( “nA boolean is {0} byte(s)”, sizeof( bool ));} }Floating-Point ValuesNot all numbers are whole numbers. When you need to use numbers that have decimals, you mustuse different data types The two primary types are float and double.flo a tA float is a data type for storing numbers with decimal places.dou bl eVariables of type double are stored in 8 bytes of memory. This means that they can be much biggerthan a float.deci m a lA data type that stores a floating-point number in 16 bytes. The precision of a decimal variable isbetter than that of the other floating-point types. This generally makes it better for storingfinancial values. The suffixes m and M designate a decimal literal.BooleanC# has a Boolean data type called a bool. The value of a bool is either true or false, which are C#keywords.This means that you can actually store true and false in a data type of bool.charA data type that stores a single Unicode character in 2 bytes.EnumerationAn enum is a value type with a set of related named constants often referred to as an enumeratorlist. The enum keyword is used to declare an enumeration. It is a primitive data type, which is userdefined.Enums type can be integer (float, int, byte, double etc.). But if you used beside int it has to be cast.
  • enum is used to create numeric constants in .NET framework. All member of enum are of enumtype. There must be a numeric value for each enum type.The default underlying type of the enumeration elements is int. By default, the first enumeratorhas the value 0, and the value of each successive enumerator is increased by 1.enum Dow {Sat, Sun, Mon, Tue, Wed, Thu, Fri};Program to demonstrate how to create and Use an Enum:using System;namespace example_enum{ class Program { public enum DayofWeek { Sunday = 1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday } static void Main(string[] args) { Console.WriteLine("Day of week {0} {1}", (int)DayofWeek.Sunday, DayofWeek.Sunday); Console.WriteLine("Day of week {0} {1}", (int)DayofWeek.Monday, DayofWeek.Monday); Console.WriteLine("Day of week {0} {1}", (int)DayofWeek.Tuesday, DayofWeek.Tuesday); Console.WriteLine("Day of week {0} {1}", (int)DayofWeek.Wednesday,DayofWeek.Wednesday); Console.WriteLine("Day of week {0} {1}", (int)DayofWeek.Thursday, DayofWeek.Thursday); Console.WriteLine("Day of week {0} {1}", (int)DayofWeek.Friday, DayofWeek.Friday); Console.WriteLine("Day of week {0} {1}", (int)DayofWeek.Saturday, DayofWeek.Saturday); Console.ReadLine(); } }}Some points about enum: • enums are enumerated data type in c#. • enums are not for end-user, they are meant for developers. • enums are strongly typed constant. They are strongly typed, i.e. an enum of one type may not be implicitly assigned to an enum of another type even though the underlying value of their members are the same. • Enumerations (enums) make your code much more readable and understandable. • enum values are fixed. enum can be displayed as a string and processed as an integer. • The default type is int, and the approved types are byte, sbyte, short, ushort, uint, long, and ulong.
  • • Every enum type automatically derives from System.Enum and thus we can use System.Enum methods on enums. • Enums are value types and are created on the stack and not on the heap.You give two same values in enum type?Yes we can have same value in enum type. Example when we want to set priority options likeNormal 0Excellent 1Default 0Good 3Enumeration MembersThe members of an enumeration are the constants declared in the enumeration and the membersinherited from the enumeration’s direct base class System.Enum and the indirect base classesSystem.ValueType and object.Reference DataType: 1. ArraysIn C#, an array index starts at zero. That means the first item of an array starts at the 0 th position.The position of the last item on an array will total number of items - 1. So if an array has 10 items,the last 10th item is at 9th position. In C#, arrays can be declared as fixed length or dynamic.A fixed length array can store a predefined number of items.A dynamic array does not have a predefined size. The size of a dynamic array increases as you addnew items to the array. You can declare an array of fixed length or dynamic. You can even changea dynamic array to static after it is defined. Elements: The individual data items of an array are called elements. All elements of an array must be of the same type. Rank/dimensions: Arrays can have any positive number of dimensions. The number of dimensions an array has is called its rank. Dimension length: Each dimension of an array has a length, which is the number of positions in that direction. Array length: The total number of elements contained in an array, in all dimensions, is called the length of the array.Lets take a look at simple declarations of arrays in C#. The following code snippet defines thesimplest dynamic array of integer types that does not have a fixed size.int[] intArray;The following code snippet declares an array that can store 5 items only starting from index 0 to 4.int[] intArray;
  • intArray = new int[5];The following code snippet declares an array that can store 100 items starting from index 0 to 99.int[] intArray;intArray = new int[100];Defining arrays of different typesIn the previous code snippet, we saw how to define a simple array of integer type. Similarly, wecan define arrays of any type such as double, character, and string.In C#, arrays are objects. That means that declaring an array doesnt create an array. Afterdeclaring an array, you need to instantiate an array by using the "new" operator.The following code snippet defines arrays of double, char, bool, and string data types.double[] doubleArray = new double[5];char[] charArray = new char[5];bool[] boolArray = new bool[2];string[] stringArray = new string[10];Initializing ArraysWhen any type of array is created, each of the elements is automatically initialized to the defaultvalue for the type. The default values for the predefined types are 0 for integer types, 0.0 forfloating point types, false for Booleans, and null for reference types.The following code snippet creates an array of 3 items and values of these items are added whenthe array is initialized.// Initialize a fixed arrayint[] staticIntArray = new int[3] {1, 3, 5};Alternative, we can also add array items one at a time as listed in the following code snippet.// Initialize a fixed array one item at a timeint[] staticIntArray = new int[3];staticIntArray[0] = 1;staticIntArray[1] = 3;staticIntArray[2] = 5;The following code snippet declares a dynamic array with string values.// Initialize a dynamic array items during declarationstring[] strArray = new string[] { "Mahesh Chand", "Mike Gold", "Raj Beniwal", "Praveen Kumar","Dinesh Beniwal" };Accessing Arrays
  • We can access an array item by passing the item index in the array. The following code snippetcreates an array of three items and displays those items on the console.// Initialize a fixed array one item at a timeint[] staticIntArray = new int[3];staticIntArray[0] = 1;staticIntArray[1] = 3;staticIntArray[2] = 5;// Read array items one by oneConsole.WriteLine(staticIntArray[0]);Console.WriteLine(staticIntArray[1]);Console.WriteLine(staticIntArray[2]);This method is useful when you know what item you want to access from an array. If you try topass an item index greater than the items in array, you will get an error.Accessing an array using a foreach LoopThe foreach control statement (loop) is used to iterate through the items of an array. For example,the following code uses foreach loop to read all items of an array of strings.// Initialize a dynamic array items during declarationstring[] strArray = new string[] { "Mahesh Chand", "Mike Gold", "Raj Beniwal", "Praveen Kumar","Dinesh Beniwal" };// Read array items using foreach loopforeach (string str in strArray){ Console.WriteLine(str);}Array TypesArrays can be divided into the following four categories. Ar Single-dimensional arrays S Multidimensional arrays or rectangular arrays M Jagged arrays J Mixed arrays.Single Dimension ArraysSingle-dimensional arrays are the simplest form of arrays. These types of arrays are used to storenumber of items of a predefined type. All items in a single dimension array are stored contiguouslystarting from 0 to the size of the array -1.
  • The following code declares an integer array that can store 3 items. As you can see from the code,first I declare the array using [] bracket and after that I instantiate the array by calling the newoperator.int[] intArray;intArray = new int[3];Array declarations in C# are pretty simple. You put array items in curly braces ({}). If an array is notinitialized, its items are automatically initialized to the default initial value for the array type if thearray is not initialized at the time it is declared.The following code declares and initializes an array of three items of integer type.int[] staticIntArray = new int[3] {1, 3, 5};The following code declares and initializes an array of 5 string items.string[] strArray = new string[5] { "Mahesh", "Mike", "Raj", "Praveen", "Dinesh" };You can even directly assign these values without using the new operator.string[] strArray = { "Mahesh", "Mike", "Raj", "Praveen", "Dinesh" };You can initialize a dynamic length array as follows:string[] strArray = new string[] { "Mahesh", "Mike", "Raj", "Praveen", "Dinesh" };Multi-Dimensional ArraysA multi-dimensional array, also known as a rectangular array is an array with more than onedimension. The form of a multi-dimensional array is a matrix.Declaring a multi-dimensional arrayA multi dimension array is declared as following:string[,] mutliDimStringArray;A multi-dimensional array can be fixed-sized or dynamic sized.Initializing multi-dimensional arraysThe following code snippet is an example of fixed-sized multi-dimensional arrays that defines twomulti dimension arrays with a matrix of 3x2 and 2x2. The first array can store 6 items and secondarray can store 4 items. Both of these arrays are initialized during the declaration.int[,] numbers = new int[3, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 } };string[,] names = new string[2, 2] { { "Rosy", "Amy" }, { "Peter", "Albert" } };Now lets see examples of multi-dimensional dynamic arrays where you are not sure of thenumber of items of the array. The following code snippet creates two multi-dimensional arrayswith no limit.int[,] numbers = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } };string[,] names = new string[,] { { "Rosy", "Amy" }, { "Peter", "Albert" } };
  • You can also omit the new operator as we did in single dimension arrays. You can assign thesevalues directly without using the new operator. For example:int[,] numbers = { { 1, 2 }, { 3, 4 }, { 5, 6 } };string[,] names = { { "Rosy", "Amy" }, { "Peter", "Albert" } };We can also initialize the array items one item at a time. The following code snippet is an exampleof initializing array items one at a time.int[,] numbers = new int[3, 2];numbers[0, 0] = 1;numbers[1, 0] = 2;numbers[2, 0] = 3;numbers[0, 1] = 4;numbers[1, 1] = 5;numbers[2, 1] = 6;Accessing multi-dimensional arraysA multi-dimensional array items are represented in a matrix format and to access its items, weneed to specify the matrix dimension. For example, item(1,2) represents an array item in thematrix at second row and third column.The following code snippet shows how to access numbers array defined in the above code.Console.WriteLine(numbers[0,0]);Console.WriteLine(numbers[0, 1]);Console.WriteLine(numbers[1, 0]);Console.WriteLine(numbers[1, 1]);Console.WriteLine(numbers[2, 0]);Console.WriteLine(numbers[2, 2]);Finding length and rank of arrayConsole.WriteLine("Array is fixed size");Console.WriteLine("Size :" + intArray.Length);Console.WriteLine("Rank :" + intArray.Rank);Jagged ArraysJagged arrays are arrays of arrays. The elements of a jagged array are other arrays.Declaring Jagged Arrays
  • Declaration of a jagged array involves two brackets. For example, the following code snippetdeclares a jagged array that has three items of an array.int[][] intJaggedArray = new int[3][];The following code snippet declares a jagged array that has two items of an array.string[][] stringJaggedArray = new string[2][];Initializing Jagged ArraysBefore a jagged array can be used, its items must be initialized. The following code snippetinitializes a jagged array; the first item with an array of integers that has two integers, second itemwith an array of integers that has 4 integers, and a third item with an array of integers that has 6integers.// Initializing jagged arraysintJaggedArray[0] = new int[2];intJaggedArray[1] = new int[4];intJaggedArray[2] = new int[6];We can also initialize a jagged arrays items by providing the values of the arrays items. Thefollowing code snippet initializes item an arrays items directly during the declaration.// Initializing jagged arraysintJaggedArray[0] = new int[2]{2, 12};intJaggedArray[1] = new int[4]{4, 14, 24, 34};intJaggedArray[2] = new int[6] {6, 16, 26, 36, 46, 56 };Accessing Jagged ArraysWe can access a jagged arrays items individually in the following way:Console.Write(intJaggedArray3[0][0]);Console.WriteLine(intJaggedArray3[2][5]);We can also loop through all of the items of a jagged array. The Length property of an array helpsa lot; it gives us the number of items in an array. The following code snippet loops through all ofthe items of a jagged array and displays them on the screen.// Loop through all itesm of a jagged arrayfor (int i = 0; i < intJaggedArray3.Length; i++){ System.Console.Write("Element({0}): ", i); for (int j = 0; j < intJaggedArray3[i].Length; j++) {
  • System.Console.Write("{0}{1}", intJaggedArray3[i][j], j == (intJaggedArray3[i].Length - 1) ? "" :" "); } System.Console.WriteLine();}Mixed ArraysMixed arrays are a combination of multi-dimension arrays and jagged arrays. The mixed arraystype is removed from .NET 4.0. I have not really seen any use of mixed arrays. You can do anythingyou want with the help of multi-dimensional and jagged arrays.A Simple ExampleHere is a complete example listed in Listing 1 that demonstrates how to declare all kinds of arraysthen initialize them and access them.To test this code, create a console application using Visual Studio 2010 or Visual C# Express andcopy and paste this code.Console.WriteLine("Single Dimension Array Sample");string[] strArray = new string[] { "Mahesh Chand", "Mike Gold", "Raj Beniwal", "Praveen Kumar","Dinesh Beniwal" };foreach (string str in strArray){ Console.WriteLine(str);}Console.WriteLine("-----------------------------");Console.WriteLine("Multi-Dimension Array Sample");string[,] string2DArray = new string[2, 2] { { "Rosy", "Amy" }, { "Peter", "Albert" } };foreach (string str in string2DArray){ Console.WriteLine(str);}Console.WriteLine("-----------------------------");Console.WriteLine("Jagged Array Sample");int[][] intJaggedArray3 ={ new int[] {2,12}, new int[] {14, 14, 24, 34}, new int[] {6, 16, 26, 36, 46, 56}};// Loop through all itesm of a jagged arrayfor (int i = 0; i < intJaggedArray3.Length; i++){ Console.Write("Element({0}): ", i); for (int j = 0; j < intJaggedArray3[i].Length; j++)
  • { Console.Write("{0}{1}", intJaggedArray3[i][j], j == (intJaggedArray3[i].Length - 1) ? "" : " "); } Console.WriteLine();}Console.WriteLine("-----------------------------");}}int[][] jaggedArray = new int[][]{new int[] {1,3,5,7,9},new int[] {0,2,4,6},new int[] {11,22}};How would you make an assignment to replace the 11 in the third element above with the value25?Answer: well, 11 is the first element of the third array, so our code would be jaggedArrray[2][0];2. InterfacesAn interface contains only the signatures of methods, properties, events or indexers. A class orstruct that implements the interface must implement the members of the interface that arespecified in the interface definition. In the following example, class ImplementationClass mustimplement a method named SampleMethod that has no parameters and returns void.Example:1interface ISampleInterface{ void SampleMethod();}class ImplementationClass : ISampleInterface{ // Explicit interface member implementation: void ISampleInterface.SampleMethod() { // Method implementation. } static void Main() { // Declare an interface instance. ISampleInterface obj = new ImplementationClass();
  • // Call the member. obj.SampleMethod(); }}Example2:using System;interface Sample{ double AreaOfCircle(double Radius); double curcum(double Radius1); void OddEven(int a);}class Test : Sample{ public double AreaOfCircle(double Radius) { return Radius * Radius * 3.141; } public double curcum(double Radius1) { return 2 * 3.141 * Radius1; } public void OddEven(int a) { if (a % 2 == 0) Console.WriteLine("Even"); else Console.WriteLine("Odd"); } static void Main() { Test obj = new Test(); int x; double T1, t2, Area, C; Area = double.Parse(Console.ReadLine()); C = double.Parse(Console.ReadLine()); Console.WriteLine("Insert Value to Check Even or Odd"); x = int.Parse(Console.ReadLine()); T1 = obj.AreaOfCircle(Area); t2 = obj.curcum(C); Console.WriteLine("Area={0}, Curcum={1}", T1, t2);
  • obj.OddEven(x); }}An interface can be a member of a namespace or a class and can contain signatures of thefollowing members: • Methods • Properties • Indexers • EventsAn interface can inherit from one or more base interfaces.A class that implements an interface can explicitly implement members of that interface. Anexplicitly implemented member cannot be accessed through a class instance, but only through aninstance of the interface. 3. StringThe string type represents a sequence of zero or more Unicode characters. Although string is areference type, the equality operators (== and !=) are defined to compare the values of stringobjects, not references. This makes testing for string equality more intuitive. For example:string a = "hello";string b = "h";// Append to contents of bb += "ello";Console.WriteLine(a == b);Console.WriteLine((object)a == (object)b);This displays "True" and then "False" because the content of the strings are equivalent, but a andb do not refer to the same string instance.The + operator concatenates strings:string a = "good " + "morning";This creates a string object that contains "good morning".Strings are immutable--the contents of a string object cannot be changed after the object iscreated, although the syntax makes it appear as if you can do this. For example, when you writethis code, the compiler actually creates a new string object to hold the new sequence ofcharacters, and that new object is assigned to b. The string "h" is then eligible for garbagecollection.
  • string b = "h";b += "ello";The [] operator can be used for readonly access to individual characters of a string:string str = "test";char x = str[2]; // x = s;String literals are of type string and can be written in two forms, quoted and @-quoted. Quoted"good morning" // a string literalString literals can contain any character literal. Escape sequences are included. The followingexample uses escape sequence for backslash, u0066 for the letter f, and n for newline.string a = "u0066n";Console.WriteLine(a);NoteThe escape code udddd (where dddd is a four-digit number) represents the Unicode characterU+dddd. Eight-digit Unicode escape codes are also recognized: Udddddddd.Verbatim string literals start with @ and are also enclosed in double quotation marks. Forexample:@"good morning" // a string literalThe advantage of verbatim strings is that escape sequences are not processed, which makes iteasy to write, for example, a fully qualified file name:@"c:DocsSourcea.txt" // rather than "c:DocsSourcea.txt"To include a double quotation mark in an @-quoted string, double it:@"""Ahoy!"" cried the captain." // "Ahoy!" cried the captain.Another use of the @ symbol is to use referenced (/reference) identifiers that are C# keywords.class SimpleStringTest{ static void Main() { string a = "u0068ello "; string b = "world"; Console.WriteLine( a + b ); Console.WriteLine( a + b == "Hello World" ); // == performs a case-sensitive comparison
  • }}/* Output: hello world False */ 4. ClassClasses are declared using the keyword class, as shown in the following example:class TestClass{ // Methods, properties, fields, events, delegates // and nested classes go here.}Unlike C++, only single inheritance is allowed in C#. In other words, a class can inheritimplementation from one base class only. However, a class can implement more than oneinterface. The following table shows examples of class inheritance and interface implementation:Inheritance ExampleNone class ClassA { }Single class DerivedClass: BaseClass { }None, implements two interfaces class ImplClass: IFace1, IFace2 { }Single, implements one interface class ImplDerivedClass: BaseClass, IFace1 { }The access levels protected and private are only allowed on nested classes.A class can contain declarations of the following members: • Constructors ,Destructors ,Constants ,Fields , Methods , Properties ,Indexers ,Operators , Events , Classes , Interfaces , Structs Example: class Child { private int age; private string name; // Default constructor: public Child() { name = "N/A"; }
  • // Constructor: public Child(string name, int age) { this.name = name; this.age = age; } // Printing method: public void PrintChild() { Console.WriteLine("{0}, {1} years old.", name, age); }}class StringTest{ static void Main() { // Create objects by using the new operator: Child child1 = new Child("Craig", 11); Child child2 = new Child("Sally", 10); // Create an object using the default constructor: Child child3 = new Child(); // Display results: Console.Write("Child #1: "); child1.PrintChild(); Console.Write("Child #2: "); child2.PrintChild(); Console.Write("Child #3: "); child3.PrintChild(); }}
  • Basics of C# RemainingEscape SequenceKeywordsKeywords are the specific terms that have special meaning and, therefore, make up a language.abstract as base bool breakbyte case catch char checkedclass const continue decimal defaultdelegate do double else enumevent explicit extern false finallyfixed float for foreach gotoif implicit in int interfaceinternal is lock long namespacenew null object operator outoverride params private protected publicreadonly ref return sbyte sealedshort sizeof stackalloc static stringstruct switch this throw truetry typeof uint ulong uncheckedunsafe ushort using virtual void
  • volatile whileB) NamespacesC# programs are organized using namespaces. Namespaces provide a hierarchical means oforganizing the elements of one or more programs. They also provide a way of presenting programelements that are exposed to other programs. For instance in our exampleusing System;class myClass{ static void Main() { Console.WriteLine("Hello World"); }}The statement – “using system;” helps us use the “Console” class in it. A namespace-declarationconsists of the keyword namespace, followed by a namespace name and bodynamespace Company1.Dept2{ class manager {} class emp {}}namespace Company1{ namespace Dept2 { class manager {} class emp {} }}c. Constants: A constant is a class member that represents a constant value: a value that can becomputed at compile-time. Constants can depend on other constants within the same program.class myClass{ public const int A = 1; public const int B = A + 1;}
  • i) Comments: Two forms of comments are supported: delimited comments and single-linecomments. A delimited comment begins with the characters /* and ends with the characters */.Delimited comments can occupy a portion of a line, a single line, or multiple lines. A single-linecomment begins with the characters // and extends to the end of the line./* This is my First ProgramThis is where it gets started*/class myFirstProgram{ static void Main() { System.Console.WriteLine("Welcome Aboard!"); // Comment }}Member AccessDeclarations of members allow control over member access. When access to a particular memberis allowed, the member is said to be accessible. Conversely, when access to a particular member isdisallowed, the member is said to be inaccessible.Declared AccessibilityThe declared accessibility of a member can be one of the following. • Public, which is selected by including a public modifier in the member declaration. The intuitive meaning of public is "access not limited." • Protected, which is selected by including a protected modifier in the member declaration. The intuitive meaning of protected is "access limited to the containing class or types derived from the containing class." • Internal, which is selected by including an internal modifier in the member declaration. The intuitive meaning of internal is "access limited to this program." • Protected internal (meaning protected or internal), which is selected by including both a protected and an internal modifier in the member declaration. The intuitive meaning of protected internal is "access limited to this program or types derived from the containing class." • Private, which is selected by including a private modifier in the member declaration. The intuitive meaning of private is "access limited to the containing type."Depending on the context in which a member declaration takes place, only certain types ofdeclared accessibility are permitted. Furthermore, when a member declaration does not include
  • any access modifiers, the context in which the declaration takes place determines the defaultdeclared accessibility. • Namespaces implicitly have public declared accessibility. No access modifiers are allowed on namespace declarations. • Types declared in compilation units or namespaces can have public or internal declared accessibility and default to internal declared accessibility. • Class members can have any of the five kinds of declared accessibility and default to private declared accessibility. (Note that a type declared as a member of a class can have any of the five kinds of declared accessibility, but a type declared as a member of a namespace can have only public or internal declared accessibility.) • Struct members can have public, internal, or private declared accessibility and default to private declared accessibility because structs are implicitly sealed. Struct members introduced in a struct (that is, not inherited by that struct) cannot have protected or protected internal declared accessibility. (Note that a type declared as a member of a struct can have public, internal, or private declared accessibility, but a type declared as a member of a namespace can have only public or internal declared accessibility.) • Interface members implicitly have public declared accessibility. No access modifiers are allowed on interface member declarations. • Enumeration members implicitly have public declared accessibility. No access modifiers are allowed on enumeration member declarations. Basics of C# • Literals are straightforward hard-coded values • In addition to C# keywords and literals, other words are used within C# programs. These words are considered identifiers • Expressions are like phrases • Statements are like sentences; they complete a single thought. A statement generally ends with a punctuation character—a semicolon (;). • One general statement deserves special mention: the empty statement. As you learned previously, statements generally end with a semicolon. You can actually put a semicolon on a line by itself. This is a statement that does nothing. Because there are no expressions to execute, the statement is considered an empty statement. • A variable is a named data storage location in your computer’s memory.
  • • By default, a numeric literal is either an integer or a double. It is an int if it is a whole number, and it is a double if it is a floating-point number. • The WriteLine() routine writes information and then goes to a new line. The Write()routine does not go to a new line when information is written. • The {0} is a placeholder for a valueOperatorsOperators are used to manipulate information.Types of OperatorsOperators can be broken into a number of categories:• The basic assignment operator• Mathematical/arithmetic operators• Relational operators• The conditional operator• Other operators (type, size)In addition to these categories, it is important to understand the structure of operator statements.Three types of operator structures exist:• Unary• Binary• TernaryUnary Operator TypesUnary operators are operators that impact a single variable.Syntax[operator][variable]or[variable][operator]These operators add 1 to the value or subtract 1 from the value of a variable. The followingexample adds 1 to x:++x;It is the same as saying this:x = x + 1;Additionally, the following subtracts 1 from x:
  • --x;It is the same as saying this:x = x – 1;Binary Operator TypesWhereas unary operator types use only one variable, binary operator types work with twovariablesSyntax[variable1][operator][variable2]Ternary Operator TypesTernary operators are the most complex operator type to work with. As the name implies, thistype of operator works on three variables. C# has only one true ternary operator, the conditionaloperator. ? : is only ternary operator in C#.C n tn ? if_ resa m t : if_false_statement; o do ii t u_t ee tnPunctuatorsPunctuators are a special form of operator that helps you format your code, do multipleoperations at once, and simply signal information to the compiler.• Semicolon—The primary use of the semicolon is to end each C# statement. A semicolon is alsoused with a couple of the C# statements that control program flow.• Comma—The comma is used to stack multiple commands on the same line. The most commontime to use the comma is when declaring multiple variables of the same type:int var1, var2, var3;Parentheses, ()—Parentheses are used in multiple places. Additionally, parentheses are used withfunctions.Braces, {}—Braces are used to group pieces of code. You have seen braces used to encompassclasses in many of the examples. You also should have noticed that braces are always used inpairs. 1. Assignment Operator:The first operator that you need to know about is the basic assignment operator, which is anequals sign (=).
  • x = y = 123;This might look a little weird; however, it is legal C# code. The value on the right of the equals signis evaluated. In this case, the far right is 123, which is placed in the variable y. Then the value of yis placed in the variable x. The end result is that both x and y equal 123.1 + x = y; //error 2. Mathematical/Arithmetic OperatorsAmong the most commonly used operators are the mathematical operators. All the basic mathfunctions are available within C#, including addition, subtraction, multiplication, division, andmodulus (remaindering).Adding and SubtractingFor addition and subtraction, you use the additive operators. As you should expect, for addition,the plus operator (+) is used. For subtraction, the minus (-) operator is used. The general format ofusing these variables is as follows:NewVal = Value1 + Value2;NewVal2 = Value1 – Value2;Multiplicative OperationsAn easier way to double the value of a variable is to multiply it by two. Three multiplicativeoperators commonly are used in C#:• For multiplication, the multiplier (or times) operator, which is an asterisk (*)• For division, the divisor operator, which is a forward slash (/)• For obtaining remainders, the remaindering (also called modulus) operator, which is thepercentage sign (%)Multiplication and division are done in the same manner as addition and subtraction. To multiplytwo values, you use the following format:NewVal = Value1 * Value2;Compound Arithmetic Assignment OperatorsThe compound operators provide a concise method for performing a math operation andassigning it to a value
  • 3. Relational OperatorsThe relational operators are used to compare two valuesWhen making comparisons with relational operators, you get one of two results: true or false.Consider the following comparisons made with the relational operators: • 5 < 10 5 is less than 10, so this is true. • 5 > 10 5 is not greater than 10, so this is false. • 5 == 10 5 does not equal 10, so this is false. • 5 != 10 5 does not equal 10, so this is true.4. Conditional / Logical OperatorsIn many cases, you will want to do more than one comparison to determine whether a block ofcode should be executed. The conditional logical operators enable you to do multiple comparisonswith relational operators. The two conditional logical operators that you will use are the ANDoperator (&&) and the OR operator (||).
  • • The Conditional AND OperatorThe logical AND operator (&&) enables you to verify that all conditions are met. You can rewritethe previous example as follows:If( sex == female && age >= 21 ){// This person is a female that is 21 years old or older.} • The Conditional OR OperatorSometimes you do not want all the conditions to be true: Instead, you need only one of a numberof conditions to be true. For example, you want might want to execute some code if the day ofweek is Saturday or Sunday. In these cases, you use the logical OR operator (||).if( day equals sunday OR day equals saturday ){// do statements} 5. OTHER OPERATORS sizeof Operator • This operator is used to determine the size of a value in memory. • The sizeof operator can be applied only to value types, not reference types. • The sizeof operator can only be used in the unsafe mode. • The sizeof operator cannot be overloaded. EXAMPLEclass MainClass { // unsafe not required for primitive types static void Main() { Console.WriteLine("The size of short is {0}.", sizeof(short)); Console.WriteLine("The size of int is {0}.", sizeof(int)); Console.WriteLine("The size of long is {0}.", sizeof(long)); } } /* Output: The size of short is 2. The size of int is 4.
  • The size of long is 8. */  Typeof OperatorThe typeof operator cannot be overloaded. To obtain the run-time type of an expression, you canuse the .NET Framework method GetType.Exampletypeof(type)using System;class GetTypeTest{ public static void Main() { int radius = 3; Console.WriteLine("Area = {0}", radius*radius*Math.PI); Console.WriteLine("The type is {0}", (radius*radius*Math.PI).GetType()); }} Operator PrecedenceOften multiple operators are used in a single statement. When this happens, a lot of issues seemto arise. Consider the following: Answer = 4 * 5 + 6 / 2 – 1;Different types of operators are executed in a set order, called operator precedence. The wordprecedence is used because some operators have a higher level of precedence than others.
  • Changing Precedence Order We can change the order of precedence by using parentheses punctuatorsConditional StatementIf-else StatementThe switch statement: Based on the value of the switch expression. The switch statement matchesa switch label and executes the statement(s) that corresponds to itExample:switch (iMatch) { case 0: Matched_Zero(); break; case 1: Matched_One(); break; default: Matched_None(); break;}
  • switch with Gotosint state = 0;int ch = Console.Read();switch (state){case 0: if (ch == a) { ch = Console.Read(); goto case 1; }else if (ch == c) goto case 2;else goto default;case 1: if (ch == b) { ch = Console.Read(); goto case 1; }else if (ch == c) goto case 2;else goto default;case 2: Console.WriteLine("input valid"); break;default: Console.WriteLine("illegal character {0}", ch); break;}k) Iteration statements: Iteration statements repeatedly execute an statement.Types of iteration statements:
  • while-statement• Exmaple: calculate numbers in reverse order using System; class WhileLoop { public static void Main() { int myInt = 10; while (myInt > 0) { Console.Write("{0} ", myInt); myInt--; } Console.WriteLine(); Console.ReadLine(); } }do-statementExmaple: calculate Sum of First 10 Numbersusing System;class MainClass{ static void Main(string[] args) { int a = 0, sum=0; do { sum+= a; a++; } while (a <= 10); Console.WriteLine(sum); Console.ReadLine(); }}for-statement
  • Exmaple: calculate Prime Numbersusing System;class MainClass{ public static void Main() { int num; int i; int factor; bool isprime; for (num = 2; num < 20; num++) { isprime = true; factor = 0; // see if num is evenly divisible for (i = 2; i <= num / 2; i++) { if ((num % i) == 0) { // num is evenly divisible -- not prime isprime = false; factor = i; } } if (isprime) Console.WriteLine(num + " is prime."); Console.ReadLine(); } } } foreach-statement Exmaple: Display Members of Array using System; class ForEachLoop { public static void Main() { string[] names = {"Cheryl", "Joe", "Matt", "Robert"}; foreach (string person in names) { Console.WriteLine("{0} ", person); } } }
  • Inheritance  The concept of inheritance gives us the ability to create a new class based on an existing  class.  The new class can use all the features of the original class, it can override existing features, it can extend existing features, or it can add its own featuresInheritance RelationshipLeft to right: one to ManyRight to Left: One to OneBasic Terms  Base class The original class.  Parent class/SuperClass Another name for a base class.  Derived class A new class, created by inheriting from a base class.  Child class/Sub Class Another name for a derived class.  Single inheritance A derived class created from only one base class. C# supports only single inheritance.  Multiple inheritance A derived class created from two or more base classes. C# does not support multiple inheritance.Class Inheritance in C#  When we define a class, say class-name, we can give the name of the superclass, super- class-name, of the class.  Syntax class-modifier class class-name: super-class-name { declarations }class A {}class B: A {}B is said to be a subclass of A, and A a superclass of B. A is also called the base class of B
  • Exampleusing System;public class ParentClass{ public ParentClass() { Console.WriteLine("Parent Constructor."); } public void print() { Console.WriteLine("Im a Parent Class."); }}public class ChildClass : ParentClass{ public ChildClass() { Console.WriteLine("Child Constructor."); } public static void Main() { ChildClass child = new ChildClass(); child.print(); Console.ReadLine(); }}using System;// declares the enumpublic enum Volume{ Low, Medium, High}// demonstrates how to use the enumclass EnumSwitch{ static void Main() { // create and initialize // instance of enum type Volume myVolume = Volume.Medium; // make decision based // on enum value
  • switch (myVolume) { case Volume.Low: Console.WriteLine("The volume has been turned Down."); break; case Volume.Medium: Console.WriteLine("The volume is in the middle."); break; case Volume.High: Console.WriteLine("The volume has been turned up."); break; } Console.ReadLine(); }}