55
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# Program 1. Compilation - Converting source code in C# language into bytecode in IL (Intermediate Language) using C# compiler. This step is usually done by the Microsoft C# compiler like the "csc" command line tool, which will actually write the bytecode in a PE (Portable Executable) file. 2. Execution - Converting bytecode in Intermediate Language into native code in machine language on-the-fly (or just-in- time) and executing the native code in a single step. This step is usually done by the Microsoft CLR (Common Language Runtime), which will be invoked when a PE file with IL bytecode is loaded into the Windows system.

C# by Zaheer Abbas Aghani

Embed Size (px)

Citation preview

Page 1: C# by Zaheer Abbas Aghani

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# Program

1. Compilation - Converting source code in C# language into bytecode in IL (Intermediate Language) using C# compiler.

This step is usually done by the Microsoft C# compiler like the "csc" command line tool, which will actually write the bytecode in a PE (Portable Executable) file.

2. Execution - Converting bytecode in Intermediate Language into native code in machine language on-the-fly (or just-in-time) and executing the native code in a single step.

This step is usually done by the Microsoft CLR (Common Language Runtime), which will be invoked when a PE file with IL bytecode is loaded into the Windows system.

Page 2: C# by Zaheer Abbas Aghani

Steps involve in C# program Development

Object 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 Object2. 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:

Page 3: C# by Zaheer Abbas Aghani

• Attributes (Field or properties)

• Behaviors (method or operation)

Eg of Class are. Teacher, Student, Car

In an OO model, some of the objects exhibit identical characteristics (properties and behaviour) 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 brake

Object:

• 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 students

Attributes

Name

Student Roll No

Year of Study CGPA

Designation Salary Employee ID Age

Behavior

Page 4: C# by Zaheer Abbas Aghani

Study GiveExam PlaySports Eat

TakeExam DevelopExam DeliverLecture Walk

Page 5: C# by Zaheer Abbas Aghani

If we see from Student’s Perspective; only following information is required

Attributes

Name Student Roll No Year of Study CGPA

Behavior

Study GiveExam PlaySports

If we see from Teacher’s Perspective; only following information is required

Attributes

Designation Salary Employee ID Age

Behavior

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

Page 6: C# by Zaheer Abbas Aghani

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 it

4. 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 Carbon

5. 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

Page 7: C# by Zaheer Abbas Aghani

Inheritance enables you to create a new class that reuses, extends, and modifies the behavior that is defined in another class. The class whose members are inherited is called the base class, and the class 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 Multi Level 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 understand

Classes

Defining a ClassTo keep things simple, a keyword called class is used to define classes. The basic structure of a class 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. Name should be meaningful.

Declaring ClassesAfter a class is defined, you use it to create objects. A class is just a definition used to create objects. A class by itself does not have the capability to hold information or actually perform routines. Instead, a class is used to declare objects. The object can then be used to hold the data and 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 of a 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 being declared.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 store information, so it needs memory reserved. The new keyword reserves the memory.

The Members of a Class

Page 8: C# by Zaheer Abbas Aghani

Member Description

Constants Constant values associated with the class

Fields/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 class

Indexers Actions associated with indexing instances of the class like an array

Operators Conversions and expression operators supported by the class

Constructors Actions required to initialize instances of the class or the class itself

Destructors Actions to perform before instances of the class are permanently discarded

Member of class can be data members or function/method members. Data members include variables 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. Accessing Data Members

When you have data members declared, you want to get to their values. To access a data member, 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);}}

Constructors

Page 9: C# by Zaheer Abbas Aghani

A constructor looks very much like a method, but with no return type and a name which is the same as the name of the class. When an object is first created its constructor is created in the memory. If user does not create constructor of the class the default constructor will be automatically 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 is created, 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 is instantiated. 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 constructor declared with the static modifier is called before the first object is created. It is called only once and 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."); } }

Page 10: C# by Zaheer Abbas Aghani

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 of parameters.

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");

Page 11: C# by Zaheer Abbas Aghani

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’s name in your program, you are, in effect, referring to the information stored there.

Naming Your Variables

To 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 with special

commands. Additionally, it is sometimes hard to read.

• Case matters (that is, upper- and lowercase letters). C# is case sensitive; thus, the names count

and 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 the

C# 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 casting

Example

Page 12: C# by Zaheer Abbas Aghani

static 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 assignmentobject obj = 3;wraps up the value 3 into a heap object

int i = 123;object o = (object)i; // boxing

• Unboxing The assignmentint x = (int) obj;unwraps the value againo = 123;i = (int)o; // unboxing

Example:using System;

Page 13: C# by Zaheer Abbas Aghani

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 Types

There are two main types of data types

1. Primitive data types2. Reference data types

1. Primitive data types

Numeric Variable Types

C# provides several different types of numeric variables. You need different types of variables because different numeric values have varying memory storage requirements and differ in the ease with 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• Enumeration

The Integral Data Types

Integral 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 are integral values.

Page 14: C# by Zaheer Abbas Aghani

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 ));}

}

Page 15: C# by Zaheer Abbas Aghani

Floating-Point ValuesNot all numbers are whole numbers. When you need to use numbers that have decimals, you must use different data types The two primary types are float and double.

floatA float is a data type for storing numbers with decimal places.doubleVariables of type double are stored in 8 bytes of memory. This means that they can be much bigger than a float.

decimalA data type that stores a floating-point number in 16 bytes. The precision of a decimal variable is better than that of the other floating-point types. This generally makes it better for storing financial 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.

Enumeration

An enum is a value type with a set of related named constants often referred to as an enumerator list. The enum keyword is used to declare an enumeration. It is a primitive data type, which is user defined. 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 enum type. There must be a numeric value for each enum type. The default underlying type of the enumeration elements is int. By default, the first enumerator has 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 {

Page 16: C# by Zaheer Abbas Aghani

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 like Normal 0 Excellent 1 Default 0 Good 3

Page 17: C# by Zaheer Abbas Aghani

Enumeration Members

The members of an enumeration are the constants declared in the enumeration and the members inherited from the enumeration’s direct base class System.Enum and the indirect base classes System.ValueType and object.

Reference DataType:

1. Arrays

In 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 add new items to the array. You can declare an array of fixed length or dynamic. You can even change a 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.

Let's take a look at simple declarations of arrays in C#. The following code snippet defines the simplest 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 types

In the previous code snippet, we saw how to define a simple array of integer type. Similarly, we can define arrays of any type such as double, character, and string.

In C#, arrays are objects. That means that declaring an array doesn't create an array. After declaring an array, you need to instantiate an array by using the "new" operator.

Page 18: C# by Zaheer Abbas Aghani

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 Arrays

When any type of array is created, each of the elements is automatically initialized to the default value for the type. The default values for the predefined types are 0 for integer types, 0.0 for floating 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 when the array is initialized.

// Initialize a fixed array int[] 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 time int[] 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 declaration string[] 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 snippet creates an array of three items and displays those items on the console.

// Initialize a fixed array one item at a time int[] staticIntArray = new int[3]; staticIntArray[0] = 1; staticIntArray[1] = 3; staticIntArray[2] = 5; // Read array items one by one Console.WriteLine(staticIntArray[0]); Console.WriteLine(staticIntArray[1]); Console.WriteLine(staticIntArray[2]);

Page 19: C# by Zaheer Abbas Aghani

This method is useful when you know what item you want to access from an array. If you try to pass an item index greater than the items in array, you will get an error.

Accessing an array using a foreach Loop

The 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 declaration string[] strArray = new string[] { "Mahesh Chand", "Mike Gold", "Raj Beniwal", "Praveen Kumar", "Dinesh Beniwal" }; // Read array items using foreach loop foreach (string str in strArray) { Console.WriteLine(str); }

Array Types

Arrays can be divided into the following four categories.

Single-dimensional arrays Multidimensional arrays or rectangular arrays Jagged arrays Mixed arrays.

Single Dimension Arrays

Single-dimensional arrays are the simplest form of arrays. These types of arrays are used to store number of items of a predefined type. All items in a single dimension array are stored contiguously starting 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 new operator.

int[] intArray; intArray = new int[3];

Array declarations in C# are pretty simple. You put array items in curly braces ({}). If an array is not initialized, its items are automatically initialized to the default initial value for the array type if the array 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.

Page 20: C# by Zaheer Abbas Aghani

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 Arrays

A multi-dimensional array, also known as a rectangular array is an array with more than one dimension. The form of a multi-dimensional array is a matrix.

Declaring a multi-dimensional array

A multi dimension array is declared as following:

string[,] mutliDimStringArray; A multi-dimensional array can be fixed-sized or dynamic sized.

Initializing multi-dimensional arrays

The following code snippet is an example of fixed-sized multi-dimensional arrays that defines two multi dimension arrays with a matrix of 3x2 and 2x2. The first array can store 6 items and second array 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 let's see examples of multi-dimensional dynamic arrays where you are not sure of the number of items of the array. The following code snippet creates two multi-dimensional arrays with 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 these values 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 example of 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;

Page 21: C# by Zaheer Abbas Aghani

numbers[2, 1] = 6;

Accessing multi-dimensional arrays

A multi-dimensional array items are represented in a matrix format and to access it's items, we need to specify the matrix dimension. For example, item(1,2) represents an array item in the matrix 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 array Console.WriteLine("Array is fixed size"); Console.WriteLine("Size :" + intArray.Length); Console.WriteLine("Rank :" + intArray.Rank);

Jagged Arrays

Jagged 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 snippet declares 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 Arrays Before a jagged array can be used, its items must be initialized. The following code snippet initializes a jagged array; the first item with an array of integers that has two integers, second item with an array of integers that has 4 integers, and a third item with an array of integers that has 6 integers.

// Initializing jagged arrays

Page 22: C# by Zaheer Abbas Aghani

intJaggedArray[0] = new int[2]; intJaggedArray[1] = new int[4]; intJaggedArray[2] = new int[6];

We can also initialize a jagged array's items by providing the values of the array's items. The following code snippet initializes item an array's items directly during the declaration. // Initializing jagged arrays intJaggedArray[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 Arrays We can access a jagged array's 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 helps a lot; it gives us the number of items in an array. The following code snippet loops through all of the items of a jagged array and displays them on the screen. // Loop through all itesm of a jagged array for (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 Arrays

Mixed arrays are a combination of multi-dimension arrays and jagged arrays. The mixed arrays type is removed from .NET 4.0. I have not really seen any use of mixed arrays. You can do anything you want with the help of multi-dimensional and jagged arrays.

A Simple Example

Here is a complete example listed in Listing 1 that demonstrates how to declare all kinds of arrays then initialize them and access them. To test this code, create a console application using Visual Studio 2010 or Visual C# Express and copy and paste this code.

Page 23: C# by Zaheer Abbas Aghani

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 array for (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 value 25?

Page 24: C# by Zaheer Abbas Aghani

Answer: well, 11 is the first element of the third array, so our code would be jaggedArrray[2][0];

2. Interfaces

An interface contains only the signatures of methods, properties, events or indexers. A class or struct that implements the interface must implement the members of the interface that are specified in the interface definition. In the following example, class ImplementationClass must implement a method named SampleMethod that has no parameters and returns void.

Example:1

interface 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) {

Page 25: C# by Zaheer Abbas Aghani

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 the following members:

Methods Properties

Indexers

Events

An interface can inherit from one or more base interfaces.

Page 26: C# by Zaheer Abbas Aghani

A class that implements an interface can explicitly implement members of that interface. An explicitly implemented member cannot be accessed through a class instance, but only through an instance of the interface.

3. String

The string type represents a sequence of zero or more Unicode characters. Although string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references. This makes testing for string equality more intuitive. For example:

string a = "hello";string b = "h";// Append to contents of 'b'b += "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 and b 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 is created, although the syntax makes it appear as if you can do this. For example, when you write this code, the compiler actually creates a new string object to hold the new sequence of characters, and that new object is assigned to b. The string "h" is then eligible for garbage collection.

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 literal

String literals can contain any character literal. Escape sequences are included. The following example uses escape sequence \\ for backslash, \u0066 for the letter f, and \n for newline.

Page 27: C# by Zaheer Abbas Aghani

string a = "\\\u0066\n";Console.WriteLine(a);

NoteThe escape code \udddd (where dddd is a four-digit number) represents the Unicode character U+dddd. Eight-digit Unicode escape codes are also recognized: \Udddddddd.

Verbatim string literals start with @ and are also enclosed in double quotation marks. For example:

@"good morning" // a string literal

The advantage of verbatim strings is that escape sequences are not processed, which makes it easy to write, for example, a fully qualified file name:

@"c:\Docs\Source\a.txt" // rather than "c:\\Docs\\Source\\a.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. Class

Classes are declared using the keyword class, as shown in the following example:

class TestClass{ // Methods, properties, fields, events, delegates // and nested classes go here.

Page 28: C# by Zaheer Abbas Aghani

}

Unlike C++, only single inheritance is allowed in C#. In other words, a class can inherit implementation from one base class only. However, a class can implement more than one interface. 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

Page 29: C# by Zaheer Abbas Aghani

{ 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(); }}

Page 30: C# by Zaheer Abbas Aghani

Basics of C# Remaining

Escape Sequence

Keywords

Keywords are the specific terms that have special meaning and, therefore, make up a language.

abstract as base bool break

byte case catch char checked

class const continue decimal default

delegate do double else enum

event explicit extern false finally

fixed float for foreach goto

if implicit in int interface

internal is lock long namespace

new null object operator out

override params private protected public

readonly ref return sbyte sealed

short sizeof stackalloc static string

struct switch this throw true

try typeof uint ulong unchecked

Page 31: C# by Zaheer Abbas Aghani

unsafe ushort using virtual void

volatile while

B) Namespaces

C# programs are organized using namespaces. Namespaces provide a hierarchical means of organizing the elements of one or more programs. They also provide a way of presenting program elements that are exposed to other programs. For instance in our example

using System; class myClass {      static void Main()      {           Console.WriteLine("Hello World");      } }

The statement – “using system;” helps us use the “Console” class in it. A namespace-declaration consists of the keyword namespace, followed by a namespace name and body

namespace 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 be computed at compile-time. Constants can depend on other constants within the same program.

class myClass {      public const int A = 1;

Page 32: C# by Zaheer Abbas Aghani

     public const int B = A + 1; }

i) Comments: Two forms of comments are supported: delimited comments and single-line comments. 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-line comment begins with the characters // and extends to the end of the line.

/* This is my First Program This is where it gets started */ class myFirstProgram {      static void Main() {           System.Console.WriteLine("Welcome Aboard!"); // Comment      } }

Member Access

Declarations of members allow control over member access. When access to a particular member is allowed, the member is said to be accessible. Conversely, when access to a particular member is disallowed, the member is said to be inaccessible.

Declared Accessibility

The 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."

Page 33: C# by Zaheer Abbas Aghani

Depending on the context in which a member declaration takes place, only certain types of declared accessibility are permitted. Furthermore, when a member declaration does not include any access modifiers, the context in which the declaration takes place determines the default declared 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

Page 34: C# by Zaheer Abbas Aghani

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 value

Operators

Operators are used to manipulate information.

Types of Operators

Operators 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

• Ternary

Unary Operator Types

Unary operators are operators that impact a single variable.

Syntax

[operator][variable]

or

[variable][operator]

Page 35: C# by Zaheer Abbas Aghani

These operators add 1 to the value or subtract 1 from the value of a variable. The following

example 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 Types

Whereas unary operator types use only one variable, binary operator types work with two

variables

Syntax

[variable1][operator][variable2]

Ternary Operator Types

Ternary operators are the most complex operator type to work with. As the name implies, this

type of operator works on three variables. C# has only one true ternary operator, the conditional

operator. ? : is only ternary operator in C#.

Condition ? if_true_statement : if_false_statement;

Punctuators

Punctuators are a special form of operator that helps you format your code, do multiple

operations 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 also

used 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 common

time 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 with

functions.

Page 36: C# by Zaheer Abbas Aghani

Braces, {}—Braces are used to group pieces of code. You have seen braces used to encompass

classes in many of the examples. You also should have noticed that braces are always used in

pairs.

1. Assignment Operator:

The first operator that you need to know about is the basic assignment operator, which is an

equals sign (=).

x = y = 123;

This might look a little weird; however, it is legal C# code. The value on the right of the equals sign

is evaluated. In this case, the far right is 123, which is placed in the variable y. Then the value of y

is placed in the variable x. The end result is that both x and y equal 123.

1 + x = y; //error

2. Mathematical/Arithmetic Operators

Among the most commonly used operators are the mathematical operators. All the basic math

functions are available within C#, including addition, subtraction, multiplication, division, and

modulus (remaindering).

Adding and Subtracting

For 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 of

using these variables is as follows:

NewVal = Value1 + Value2;

NewVal2 = Value1 – Value2;

Multiplicative Operations

An easier way to double the value of a variable is to multiply it by two. Three multiplicative

operators 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 the

percentage sign (%)

Page 37: C# by Zaheer Abbas Aghani

Multiplication and division are done in the same manner as addition and subtraction. To multiply

two values, you use the following format:

NewVal = Value1 * Value2;

Compound Arithmetic Assignment Operators

The compound operators provide a concise method for performing a math operation and

assigning it to a value

3. Relational Operators

The relational operators are used to compare two values

When 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 Operators

In many cases, you will want to do more than one comparison to determine whether a block of code should be executed. The conditional logical operators enable you to do multiple comparisons

Page 38: C# by Zaheer Abbas Aghani

with relational operators. The two conditional logical operators that you will use are the AND operator (&&) and the OR operator (||).

Page 39: C# by Zaheer Abbas Aghani

The Conditional AND Operator

The logical AND operator (&&) enables you to verify that all conditions are met. You can rewrite the previous example as follows:If( sex == female && age >= 21 ){// This person is a female that is 21 years old or older.}

The Conditional OR Operator

Sometimes you do not want all the conditions to be true: Instead, you need only one of a number of conditions to be true. For example, you want might want to execute some code if the day of week 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.

Page 40: C# by Zaheer Abbas Aghani

The size of long is 8. */

Typeof Operator

The typeof operator cannot be overloaded. To obtain the run-time type of an expression, you can use the .NET Framework method GetType.

Example

typeof(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 seem to arise. Consider the following:

Answer = 4 * 5 + 6 / 2 – 1;Different types of operators are executed in a set order, called operator precedence. The word precedence is used because some operators have a higher level of precedence than others.

Page 41: C# by Zaheer Abbas Aghani

Changing Precedence Order

We can change the order of precedence by using parentheses punctuators

Conditional Statement

If-else Statement

Page 42: C# by Zaheer Abbas Aghani

The switch statement: Based on the value of the switch expression. The switch statement matches a switch label and executes the statement(s) that corresponds to it Example:

switch (iMatch) {      case 0:           Matched_Zero();           break;      case 1:           Matched_One();           break;      default:           Matched_None();           break; }

switch with Gotos

int 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;

Page 43: C# by Zaheer Abbas Aghani

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-statement

Exmaple: calculate Sum of First 10 Numbersusing System;

class MainClass{

static void Main(string[] args) { int a = 0, sum=0;

Page 44: C# by Zaheer Abbas Aghani

do { sum+= a; a++; } while (a <= 10); Console.WriteLine(sum); Console.ReadLine(); }

}

for-statement

Exmaple: calculate Prime Numbers

using 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(); } }

}

Page 45: C# by Zaheer Abbas Aghani

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 features

Inheritance Relationship

Left to right: one to ManyRight to Left: One to One

Basic 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.

Page 46: C# by Zaheer Abbas Aghani

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("I'm a Parent Class."); }}

public class ChildClass : ParentClass { public ChildClass() { Console.WriteLine("Child Constructor."); } public static void Main() {

Page 47: C# by Zaheer Abbas Aghani

ChildClass child = new ChildClass(); child.print(); Console.ReadLine(); }}

using System;

// declares the enumpublic enum Volume{   Low,   Medium,   High}

// demonstrates how to use the enum

class 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();   }}