Tuesday, 14 February 2012

Nullable Types

Nullable types:

A Nullable type was introduced in C# 2.0 as a value type. Microsoft introduced these types for solving the problem of assigning default values to value types at the time of value type declaration.

Nullable types allow the value types that they will accept the null values instead of default values.

’?’ modifier is used in Nullable types after the data types and that allows the null values for that type.

The type before the ‘?’ modifier is known as underlying type of Nullable types.

The underlying type of Nullable types is either a value type or any parameter that is considere to value types but it won’t be reference type

int?,double ? are valid for Nullable types but string? is not a Nullable type

The underlying type must be itself a Nullable type.

If we define an object like T?, it is a alias for system.nullable

An object of a Nullable type has two public properties:

· Hasvalue:

Hasvalue property is used for bool types. If an instance’s Hasvalue is true, then that is said to be non null. If Hasvalue is false then that instance has null value .

The default value for Hasvalue is false.

· Value:

If we assign any value to instance of a Nullable type,then value property returns that value. Otherwise it throws an exception.

There is no default value for this property.

Example:

Class N

{

Static void main (string[] args)

{

int? n = null;

if (n.Hasvalue == true)

{

Console.writeLine (“n value is”+ n.value );

}

else

{

Console.writeline ( “n value is null”);

}

}

}

Anonymous Types

Anonymous types:

Anonymous types are introduced in C# 3.0 which permits object initializer to create anonymous type by using the ‘var’ keyword.

Anonymous type is a class which is created by CLR automatically at run time and this class is not visible by users.

These types can reduce the code that need to access the class properties.

Class does not need to define properties, CLR will taken at run time.

Example:

Class AT

{

Static void main (string[] args)

{

Var i=new { no= 1 , name= “ ravi”, phoneno = 9985585867};

Console. Write ( i. no + “ “ +i. name + i.phoneno );

Console.ReadLine ();

}

}

In above example,we use ‘var’ keyword to define properties for class AT in single line of code .so anonymous types are used to define properties of class in simple manner.

Partial classes and Partial methods

Partial classes:

Partial classes are the classes which are dividing into no.of classes with the same name.partial classes can declared by the keyword”partial” .

partial classes are needed when we are doing big projects that we can develop the class by many developers at a time.

The compiler combines all parts of the partial class into one at complietime and exicute that class.

Example:

Public partial class Display

{

Console.writeline(“this is first part of partial class”);

}

Public partial class Display

{

console.writeline(“this is second part of partial class”);

}

Partial methods:

A Partial class must contain atleast one partial method.

One partial method contains signature and other may contain implementation of the method.without implementation the compiler does n’t execute any partial method.

We must define these by ” partial” modifier

Partail methods can be static and they must have rerturn type.

Example:

Partial class P

{

Partial void print():

Partial class p

{

Partial void print()

{

Console.writeLine(“this is partial method”);

}

}

Public static void main()

{

P a=new P();

a.print();

}

}

Sealed Classes


Sealed classes are classes which are not inheritable.To prevent the class from inheritance we use “sealed” keyword before the class name.

If we use sealed keyword to any method that method can not be inheritable.

It can overrides the parent class method,but itself cannot be override in other classes.

Example:

Sealed class B

{

Public int i;

Public int j;

}

Class program

{

B s=new B();

s.i=345;

s.j=135;

console.writeline(“i={0},j={1}”,s.i,s.j);

}

Exceptional handling

In C#, exceptional handling provides an environment that will handle the errors in the code by using three different blocks.

· Try

· Catch

· Finally

Try block:

In try block,we can place the code which will have errors.

Syntax:

try

{

Statements://code in which error occured

}

Catch block:

Catch block handles the exception if it occurs.catch block is optional.if there is an error in try block then

only control goes to catch block.

In this block, we can handle the exception which occurred in try block.

Syntax:

Catch(exception e)

{

Statements;//handling the exception

}

Finally block:

Finally block is mandatory in exceptional handling in C #.this block exicutes irrespective of error occurred in try block.

If thereis no error in try block then control goes to finally block ,else goes to catch block and then comes to finally block.

Syntax:

finally

{

Statements;//code that will run irrespective of error

}

DELEGATES

Delegates:

Delegates are types that they describes the signature of the method.delegates give reference to a function or method.

A delegate declared by delegate keyword.

We must declare the parameters through delegate.

Example:

Class delegateExample

{

delegate int D(string s);

Public int A()

{

return 0;

}

Public int B()

{

return 0;

}

Public void static void main(string []args)

{

D d1=new D(A);

D d2=new D(B);

String mystring=”hello world”;

d2(mystring);

d1(mystring);

}

}

Constructors


Constructors are the special methods invoked when an object is first created.

The constructor is created with class name.

Some distinct characteristics of constructors:

Constructors do not have any return type.

Constructors are always public.

Constructor is automatically declared by CLR, whenever the class is instantiated.

Example:

Class A

{

A ()//constructor name same as class name

{

//body

}

}

Differences between Abstract Class and Interfaces


Abstract class

Interface

A class can extend one abstract class

Abstract class contains abstract as well as non abstract methods

In this, multiple inheritance is not supported

Abstract class defines few or none of the methods.

Abstract classes should have sub classes

Any class can extend an abstract class

A interface can extend several interfaces

Interface contains only abstract methods

In this, multiple inheritance is supported.

Interface declares all the methods

Interface must implementation by classes.

Only an interface can extend another interface.

Interfaces


Interfaces contain only the signature of the methods.

Interfaces describe common set of methods. An interface has no implementation on its own, because it contains only the definition of methods without their bodies.

Definition of the method contains method name, parameter’s name, and their data type.

Interface is declared by interface keyword.

Interfaces are used to apply multiple inheritance in code. By This feature interface is differ from abstract classes.

Interfaces can extend multiple interfaces so multiple inheritance is not the problem

Example:

Interface A

{

Void print ()

}

Interface B

{

Void print ()

}

Class C : A,B

{

Void A. print ()

{

Console.writeLine (“this is interface A’s method”);

}

Void B.print ()

{

Console.writeLine (“This is interface B’s method”);

}

Public static void main ()

{

C x= new C ();

A a=(A)x;

B b=(B)x;

a.print();

b.print();

}

Abstract class


An abstract class is a class which provides a common definition of base class that multiple derived classes can share.

Some distinct characteristics of an abstract class:

Ø We cannot create an object of the abstract class, it must be inherited.

Ø It can have abstract as well as non-abstract members in an abstract class.

Ø We must declare at least one abstract method in the abstract class.

Ø An abstract class is always public.

We need abstract classes whenever we define a template that needs to be followed by all the derived classes.

Abstract classes are specified by keyword Abstract

Example:

Abstract class A

{

Public abstract void display ();

}

Class B : A

{

Public override void display ()

{

Console.writeLine (“this is class B’s method”);

}

Class C : A

{

Public override void display ()

{

Console.writeLine (“this is class C’s method”);

}

Class program

{

Public static void main (string [] args)

{

B b=new B ();

b.display ();//calls class B’s method

C c=new C ();

c.display ();// calls class C’s method

}

}

Encapsulation:


Encapsulation is a process of hiding irrelevant data and showing relevant data to user.

In this, we can show only essential features of a class to user and background details of a class are kept hidden from user.

The user can perform limited operations on hidden data of the class by methods.

Access modifiers are used to achieve the encapsulation in object oriented programming language.

Access modifiers:

In c#.net, we have four access modifiers

· Public

· Private

· Protected

· Internal

By using this we have five accessibility levels they are

Ø Public

Ø Private

Ø Protected

Ø Internal

Ø Protected internal

Public:

it gives unrestricted access to members inside and outside a class.

Example:

Class A

{

Public int i;

}

Private:

It gives access to the members of inside the class only. If we declare private to any member, it will not access outside of the class. By default, class members are private.

Example:

Class A

{

Private int i;

Float x;//by default, it is private.

}

Protected:

It gives access to members of the class and its derived class members.

Example:

Class A

{

Protected int i;

}

Class B: A

{

Int j;

j=i;

}

Internal:

It gives access to the members that are present in the current assembly. If a member with internal access modifier is accessed from outside the assembly in which it has been defined, an error is generated.

Example:

Public class A

{

Internal int x=0;//accessible within the same assembly

}

Protected internal:

It gives access to the members that are visible either to the current assembly or to the types derived from the class in which they are declared.

polymorphism


Polymorphism is the process of defining more functionality with same name with in the class. Polymorphism is a process of one form available in different forms. We have two different types of polymorphism,

1) Compile time polymorphism/static polymorphism (overloading)

2) Runtime polymorphism/dynamic polymorphism (overriding)

Compile time polymorphism (overloading):

Compile time polymorphism is defining more functionality with the same name in the class but difference in the signature of the method. Signature of the method means the order and the type of method arguments.

In this, multiple methods declared with same name but signature will be different. The compiler decides which method will execute in compile time, so it is known as compile time polymorphism.

The main advantage of this type is execution is fast.

Overloading a method simply involves another method with the same name with in the class

Example:

Class A

{

Public void display ()

{

Console.writeLine (“this is first method”);

}

Public void display (int a, int b)//method overloading

{

Console.writeLine (“this is second method”);

}

Public void display (int a, float b)

{

Console.writeLine (“this is third method”);

}

}

Class program

{

Public static void main (string [] args)

{

A x=new A ();

x.display ();

x.display (5, 8.4);

x.display (2, 4);

}

}

Runtime polymorphism (overriding):

Runtime polymorphism is defining more functionality with the same name and same signature in the derived class.

In this, base class method is override in derived class with the keyword ‘override’. The compiler decides which method will execute in runtime, so it is known as runtime polymorphism.

Overriding occurs when a derived class has a method with same signature as a base class’s method.

The ‘base’ keyword is used to access the base method that has been overridden.

Example:

Class A

{

Public virtual void display ();

}

Class B : A

{

Public override void display ()

{

Console.writeLine (“this is class B’s method”);

}

Class C : A

{

Public override void display ()

{

Console.writeLine (“this is class C’s method”);

}

Class program

{

Public static void main (string [] args)

{

B b=new B ();

b.display ();//calls class B’s method

C c=new C ();

c.display ();// calls class C’s method

}

}

Inheritance

Inheritance:

Getting the features of one class to another class is known as inheritance.

The class which is giving features to another class is known as base class or parent class.

The class which getting the features from another class is known as derived class or child class.

Data members and methods are called as features of class.

The main advantage of inheritance is ‘code reusability’.

Types of inheritance are

1) Single inheritance

2) Multilevel inheritance

3) Hierarchical inheritance

4) Multiple inheritance

5) Hybrid inheritance

Single inheritance:

In this inheritance, there is only one base class and one derived class.

Multilevel inheritance:

In this we have many base classes and many derived classes. The classes which are acts as a base class as well as derived class known as intermediate classes.

Hierarchical inheritance:

In this, there is no. of derived classes derived from one base class.

Multiple inheritance:

In this, one class derived from multiple base classes. Multiple inheritance is not supported in c# in classes. We can achieve this by interfaces.

Hybrid inheritance:

The combination of any two inheritances is known as hybrid inheritance.


Example:

public class A

{

public void Add()

{

console.writeline("this is class A's method");

}

}

public class B : A

{

public void print ()

{

console.writeline ("this is class B's method");

}

class program

{

static void main(string[] args)

{

A x = new A ();

x.print();

B x= new B ();

x.print ();

}

}

Classes and Objects

Class:

Class is the name of type that we use to represent the relation between the data and functions or methods. In the other way, Class is a block of code which combines methods and properties for a group of objects.

Class describes the properties of objects which are present in the class. In the class, objects are categorized according to their state and behavior. By default, classes are private.

Syntax:

Class class name

{

Statements;

}

Example:

Class employee

{

String name;

int id;

Public employee (string name, int id) // constructor

{

This.name=name;

This.id=id;

}

Public void print () //method

{

Console.writeLine (“employee name is”, name);

Console.writeLine (“employee id is”, id);

}

}

Class program

{

Public static void main ()

{

employee s1=new employee ();

s1.print ();

employee s2=new employee ();

s2.print ();

}

}

Object:

Object is an instance or an entity that will represent the components of a class. Objects interact with each other through the functionality of methods in the class.

The ‘new’ operator is used to create object of a class. When we create an object, then system creates memory for data member and methods that are present in the class.

For example, we take ‘animal’ as a class then dog, cat, tiger and other animals are the objects.

COLLECTIONS IN C#

Collections

In C#, we have five types of collections.they are

· ArrayList

· Bit Array

· Hashtable

· Queue

· Stack

ArrayList:

In C# ,Arraylist is an array that can change its size according to our need.

It can support builtin types and custom types.

We have predefined methods in arraylist they are

· Add

· Insert

· Remove

· RemoveAt

· Clear

· Clone

· Equals

· Reverse

· To array

· ToString

Example:

Class program

{

Public static void main(string []args)

{

ArrayList t=new ArrayList(10);

Int i=0;

t.Add(i);

t.insert(1,++i);

foreach (int y in t)

{

Console.writeline(y);

}

t.remove(i);

t.remove(0);

t.clear();

}

}

HashTables

Hashtables are combination of keys and values that are placed according to the hashcode of key.

By hashcode key we place the objects in the hashtable.

The below example give clear idea about the hashtable.

Example:

Class hashtableexample

{

Static void main(string []args)

{

Hashtable x=new Hashtable(10);

Hashtable.synchronized(x);

x.Add(100,”Arrays”);

x.Add(200,”delegates”);

foreach (dictionaryentry i in x)

{

Console.writeline(i.value);

}

x.remove(100);

x.remove(200);

x.clear();

}

}

QUEUES

a queue represents collection of objects as first in first out(fifo) method.

In queue, the records must be entered at one end and removed from other end.

Example:

Class QueueExample

{

Static void main(string []args)

{

Queue q=new Queue(10);

int i=0;

q.Enqueue(i);

i++;

q.Enqueue(i);

foreach(int y in q)

{

Console.writeline(y);

}

q.Dequeue();

q.clear();

}

}

Structs,Enums and Arrays

Structs:

A struct provides a way to present a group of unlike variable types in a single name.it is very useful in creating user defined value types

Structs are nested in a namespace or class and it is a value type.

Syntax for declaring Structs is

(Modifiers) Struct structname

{

}

Example:

Public Struct sample

{

Public int I , j;

}

Class program

{

Public static void main (string []args)

{

Sample s=new sample ();

s.i=10;

s.j=20;

console.writeline (“ i = { 0 }, j ={ 1 }”, s.i , s.j );

}

}

Enums:

C# has the way to declare an enumerated data. This allows the programmer to provide a set of values for an instance of the group.

CLR automatically assigns each member of enumeration an integer value.

The first item is always assigned a zero followed by one.

Example:

Public enum week

{

Monday,

Tuesday,

Wednesday,

Thursday,

Friday,

Saturday,

Sunday

}

Class program

{

Public static void main (string [] args)

{

Week Today=week. Sunday;

Console.writeline (Today);

}

}

Arrays:

Array is a collection of similar data type that can be grouped by single name.

Array start with index number as zero followed by one. There are three type of arrays

· Single dimensional array

· Multidimensional array

· Jagged array

Single dimensional array:

If you want to declare elements in a single row, single dimensional array will be needed. In this there will be only one index for array members

Example:

int[] numbers = new int [5];

for ( int i=o;i< numbers. length; i++)

{

Numbers [i]= new int [4];

}

Multidimensional Arrays:

In C#, we can declare arrays by specifying the number of columns and number of rows by multidimensional arrays.

Jagged Arrays:

Some arrays contain an array of other arrays. These are called jagged arrays.

Example:

Class A

{

Static void main (string [] args)

{

String [] my array={“Hello “,”world”};

int [] myarray = new int[8];

int a,b;

for (int i=0; i< 5; i++)

{

myarray [i]=0;

}

int [][][] myarray2 =new int[3][][];//jagged array

for(a=0;a<5;a++)

myarray2[i] = new int[4][];

for (b=0;b<10;b++)

myarray2[a][b]= new int [5];

int [,] myarray =new int[5,5];//multidimensional array

for (int x=0,y=0;x<5;x++,y++)

{

myarray[x,y]=0;

}

}

}

Control statements

Control statements

In C#,there is three types of control statements

· Selection statements

· Iterator statements

· Jump statements

Selection statements:

If and if-else:

By if statement, we can access our code through condition which will be placed in ‘if’. if that condition is true then the control goes to ’if’ block otherwise control does not execute the if statements.

If(condition)

{

///statements

}

By using if-else statement, we can get the feature ‘selection’ by accessing our code in different conditions.

Here,’If’ condition is not true then the control directly goes to else block.if ‘if’ condition is true then control executes the if block and else block does not executed.

Example:

Class P

{

Static void main (string[] args)

{

Int a,b;

a =10,b=15;

if ( a > b )

{

Console.writeline (“a is greater than b”);

}

else

{

Console.writeline (“b is greater than a”);

}

}

}

Switch ….case:

In switch-case statement, it takes a single integer value in switch statement, and that value will be compared with case statements values.

If our input does not match with case statements values then ‘default’ statement will executes.

Example:

Class SwitchExample

{

Public static void main(string[] args)

{

Int a;

Console. Write (“enter a number between 1 and3”);

Console.ReadLine (a);

Switch (a)

{

Case 1:

Console.writeline (“ur number is {0}”,a);

break;

Case 2:

Console.writeline (“ur number is{0}”,a);

break;

Case 3:

Console.writeline (“ur number is{0}”,a);

break;

default:

Console.writeline (“ur number is not between 1 and 3”);

break;

}

}

}

Iterator statements:

For:

the simplest loop statement is ‘for’ statement

Syntax for ‘for’ loop is

for ( value; condition expression ; increment or/decrement )

{

Statements

}

For statement has three parts

First part is assigning a value to variable and the second part is expression and the third part is increment or decrement

Example:

Class F

{

Static void main (string [] args)

{

for (int i = 0 ; i < 10 ; i ++)

{

Console.writeline ( i );

}

}

}

For each:

This statement uses two operands,

First operand is always the type that is adding to collection or array which is implemented in second operand.

Syntax:

foreach (type identifier in array/collection)

{

Statements

}

Example:

class FE

{

Static void main( string[] args)

{

arraylist x=new arraylist(20);

foreach(int i in x)

{

Console.writeline (i);

}

}

}

While:

Another simple loop statement is ‘while’. In ‘while’ we have the condition and if that condition is true then only the while block executes.

If the the condition is false then the control ignores the while block and executes the statements followed by while block.

Syntax;

While(expression)

{

Statements

}

Example:

Class W

{

Static void main(string[] args)

{

int x=0;

While( x < 5)

{

x++;

console.writeline (x);

}

}

}

Do-While:

The another type of while loop is do-while.

In do-while, while loop executes at least once. This is the difference between do and do-while.

Syntax:

do

{

Increment or decrement;

Statements

}while(expression)

Example:

Class DW

{

Static void main (string[] args)

{

int x=0;

Do

{

X++;

Console.writeline(x);

}while (x < 7);

} }

Jump statements:

Continue:

Continue is useful whenever execution of code in the loop should return for iteration irrespective of condition.

If we use continue in while loop, then expression in while can evaluate again and remaining code will ignored.

Example:

Class c

{

Static void main(string[] args)

{

int j=0;

While (j < 14);

{

J++;

if (j = = 5)

{

J + +;

Continue;//control goes to iteration forcefully

}

}

}

}

break:

Break statement breaks the execution code with in the block or loop. By using break , control will come outside from the class forcefully.

Example;

Class B

{

Static void main (string[] args)

{

int k=o;

While (k < 15);

{

K++;

if ( k==5)

break;

}

K++;

}

}

goto:

goto command is used in the program that it will moves the control from one place to another palce forcefully.

Example:

Class G

{

Static void main (string[] args)

{

int t=o;

While (t < 15);

{

if (t ==5)

goto cleanup;

}

Cleanup:

Console.writeline (t);

}

}

Expressions and Operators

Expressions:

An expression is useful to perform a computation by using operators and operands.

In C#, we have three types of operators

· Unary operators: in this, we have only one operand.

· Binary operators: these can have two operands

· Ternary operators: it has three operands.

In c#, we have different kinds of operators

Ø Arithmetic operators:

in this type of operators, arithmetical operators are available. They are + , - , * , % , / , += , = , ++ , -- etc.by using this operators we can perform arithmetical computations like addition,substraction,multiplication,division,decrement,increment and more.

Ø Relational operators:

By using relational operators ,we can compare two expressions or values.in this we use operators like <,>,<= ,==,!=,>=

Ø Logical operatrors:

By using these operators ,we can combine two expressions into logical expressions.there three types of logical operators,they are

1. AND(&&)

2. OR (||)

3. NOT(!)

Ø Bitwise operators:

These operators evaluate the bits of a value directly

There are six logical operators

1. AND

2. OR

3. XOR

4. NOT

5. Shift left

6. Shift right

Example:

Class A

{

Static void main(string[] args)

{

int a ,b ,c ,d ,e ,f ;

a=1;

b= a + 5;

c= a + b;

c += 1;

d = a + b + c;

if (a > b)

{

e =10;

}

if (b <15 || c<5 )

{

f=3 ;

Console.writeline(f);

}

C++;

d--;

console.writeLine(c);

console.writeLine (d);

}

}