Basic Oops in C#























 


http://www.aspdotnet-suresh.com/2010/04/introduction-to-object-oriented.html


OOPS Concepts


Class:


 It is a collection of objects.


Object:


It is a real time entity.


An object can be considered a "thing"
that can perform a set of related activities. The set of activities that
the object performs defines the object's behavior. For example, the hand can
grip something or a Student(object) can give the name or address. In
pure OOPterms an object is an instance of a class


The above template describe about
object Student


Class is composed of three things
name, attributes, and operations


  publicclassstudent


{


}


studentobjstudent=newstudent ();


 


According to the above sample we can
say that Student object, named objstudent, has created out of the
student class.


In real world you will often find
many individual objects all of the same kind. As an example, there may be
thousands of other bicycles in existence, all of the same make and model. Each
bicycle has built from the same blueprint. In object-oriented terms, we say
that the bicycle is an instance of the class of objects known as bicycles. In
the software world, though you may not have realized it, you have already used
classes. For example, the Textboxcontrol, you always used, is made out
of the Textboxclass, which defines its appearance and capabilities. Each
time you drag a Textboxcontrol, you are actually creating a new instance
of the Textboxclass.


 


Encapsulation:


Encapsulation is a process of
binding the data members and member functions into a single unit.


Example for encapsulation is class. A class can contain data
structures and methods.


Consider the following class


publicclassAperture


{


public Aperture ()


{


}


protecteddouble height;


protecteddouble width;


protecteddouble thickness;


publicdouble get volume()


{


Double volume=height * width * thickness;


if (volume<0)


return 0;


return volume;


}


}

In this example we encapsulate some data such as height, width, thickness and
method Get Volume. Other methods or objects can interact with this object
through methods that have public access modifier


 


Abstraction:


Abstraction is a process of hiding
the implementation details and displaying the essential features.


Example1:
A Laptop consists of many things such as processor, motherboard, RAM, keyboard,
LCD screen, wireless antenna, web camera, usb ports, battery, speakers
etc. To use it, you don't need to know how internally LCD screens, keyboard,
web camera, battery, wireless antenna, speaker’s works.  You just
need to know how to operate the laptop by switching it on. Think about if you
would have to call to the engineer who knows all internal details of the
laptop before operating it. This would have highly expensive as well as not
easy to use everywhere by everyone.


So here the Laptop is an object
that is designed to hide its complexity.


How to abstract: - By using Access
Specifiers


.Net has five access
Specifiers


Public -- Accessible outside the class through object reference.

Private -- Accessible inside the class only through member functions.

Protected -- Just like private but Accessible in derived classes also
through member functions.


Internal -- Visible inside the assembly.Accessible through objects.

Protected Internal -- Visible inside the assembly through objects and in
derived classes outside the assembly through member functions.

Let’s try to understand by a practical example:-


publicclassClass1


    {


       
int 
i;                                             
                 
//No Access specifier means private


       
public  int
j;                                

               
// Public


       
protectedint
k;                                        
//Protected data


       
internalint
m;                           

            // Internal means visible inside assembly


       
protectedinternalint
n;       
          //inside
assembly as well as to derived classes outside assembly


       
staticint
x;                                 

        // This is
also private


       
publicstaticint
y;                    
      //Static means shared
across objects


       
[DllImport("MyDll.dll")]


       
publicstaticexternintMyFoo(); 
     //extern means declared in
this assembly defined in some other assembly


       
publicvoid myFoo2()


       
{


           
//Within a class if you create an object of same
class then you can access all data members through object reference even
private data too


           
Class1obj = newClass1();


           
obj.i =10; //Error can’t access private data through
object.But here it is accessible.:)


           
obj.j =10;


           
obj.k=10;


          
 obj.m=10;


           
obj.n=10;


      
//     obj.s =10;  //Errror
Static data can be accessed by class names only


           
Class1.x = 10;


        
//   obj.y = 10; //Errror Static data can
be accessed by class names only


           
Class1.y = 10;


  
     }


    }


 


Now letstry

to copy the same code inside Main method and try
to compile


[STAThread]


       
staticvoid Main()


       
{


          
//Access specifiers comes into picture only when you create
object of class outside the class


           
Class1 obj = newClass1();


      
//     obj.i
=10;            

//Error can’t access private data through object.


           
obj.j =10;


      //     
obj.k=10;     //Error can’t access protected data through
object.


           
obj.m=10;


           
obj.n=10;


      
//     obj.s =10;  //Errror
Static data can be accessed by class names only


           
Class1.x = 10;  //Error can’t access private
data outside class


        
//   obj.y = 10; //Errror Static data can
be accessed by class names only


        
   Class1.y = 10;


       
}


What if

Main is inside another assembly


[STAThread]


       
staticvoid Main()


       
{


          
//Access specifiers comes into picture only when you
create object of class outside the class


           
Class1 obj = newClass1();


      
//     obj.i
=10;            
//Error can’t access private data through object.


           
obj.j =10;


      //     
obj.k=10;     //Error can’t access protected data through
object.


     //     obj.m=10; // Error can’t access
internal data outside assembly


    //      obj.n=10; // Error can’t
access internal data outside assembly


 


      
//     obj.s =10;  //Errror
Static data can be accessed by class names only


           
Class1.x = 10;  //Error can’t access private
data outside class


        
//   obj.y = 10; //Errror Static data can
be accessed by class names only


           
Class1.y = 10;


       
}


In object-oriented software,
complexity is managed by using abstraction.


Abstraction is a process that involves identifying the critical
behavior of an object and eliminating irrelevant and complex details.


Inheritance:


Inheritance is a process of deriving
the new class from already existing class


C#
is a complete object oriented programming language. Inheritance is one of the
primary concepts of object-oriented programming. It allows you to reuse
existing code. Through effective use of inheritance, you can save lot of time
in your programming and also reduce errors, which in turn will increase the
quality of work and productivity. A simple example to understand inheritance in
C#.


 


Using System;


PublicclassBaseClass


{


    PublicBaseClass ()


    {


        Console.WriteLine ("Base
Class Constructor executed"
);


    }


         
                     

 


    Publicvoid Write ()


    {


        Console.WriteLine ("Write
method in Base Class executed"
);


    }


}


         
                     

 


PublicclassChildClass:
BaseClass


{


         

                     
 


    PublicChildClass ()


    {


        Console.WriteLine("Child
Class Constructor executed"
);


    }


   


    Publicstaticvoid Main ()


    {


        ChildClass CC = newChildClass ();


        CC.Write
();


    }


}


  • In the Main () method in ChildClass we create an
    instance of childclass. Then we call the write () method. If you observe
    the ChildClass does not have a write() method in it. This write () method
    has been inherited from the parent BaseClass.
  • The output of the above program is




    Output:

      Base Class Constructor executed

      Child Class Constructor executed

      Write method in Base Class executed




    this output proves that when we create an instance of a child class, the
    base class constructor will automatically be called before the child class
    constructor. So in general Base classes are automatically instantiated
    before derived classes.
  • In C# the syntax for specifying BaseClass and
    ChildClass relationship is shown below. The base class is specified by
    adding a colon, ":", after the derived class identifier and then
    specifying the base class name.

Syntax:  class ChildClassName: BaseClass


              {

                   //Body


              }


  • C# supports single class inheritance only. What this
    means is, your class can inherit from only one base class at a time. In
    the code snippet below, class C is trying to inherit from Class A and B at
    the same time. This is not allowed in C#. This will lead to a compile time
    error: Class 'C' cannot have multiple base classes: 'A' and 'B'.

publicclassA


{


}


publicclassB


{


}


publicclassC
: A, B


{


}


  • In C# Multi-Level inheritance is
    possible. Code snippet below demonstrates mlti-level
    inheritance. Class B is derived from Class A. Class C
    is derived from Class B. So class C, will have access to all members
    present in both Class A and Class B. As a result of multi-level
    inheritance Class has access to A_Method(),B_Method() and C_Method().



    Note: Classes can inherit from multiple interfaces at the
    same time. Interview Question: How can you implement multiple
    inheritance in C#? Ans :Using Interfaces. We will talk about
    interfaces in our later article.

Using System;


PublicclassA


{


    PublicvoidA_Method ()


    {


        Console.WriteLine ("Class
A Method Called"
);


    }


}


PublicclassB:
A


{


    PublicvoidB_Method ()


    {


        Console.WriteLine ("Class
A Method Called"
);


    }


}


PublicclassC:
B


{


    PublicvoidC_Method ()


    {


        Console.WriteLine ("Class
A Method Called"
);


    }


         
         


    Publicstaticvoid Main ()


    {


        C C1 = newC ();


       
C1.A_Method ();


       
C1.B_Method ();


       

C1.C_Method ();


    }


}


  • When you derive a class from a base
    class, the derived class will inherit all members of the
    base class except constructors. In the code snippet
    below class B will inherit both M1 and M2 from Class A, but you cannot
    access M2 because of the private access modifier. Class members declared
    with a private access modifier can be accessed only with in the class. We
    will talk about access modifiers in our later article.




    Common Interview Question: Are
    private class members inherited to the derived class?

    Ans: Yes, the private members
    are also inherited in the derived class but we will not be able to access
    them. Trying to access a private base class member in the derived class
    will report a compile time error.

Using System;


PublicclassA


{


    Publicvoid M1 ()


    {


    }


    Privatevoid M2 ()


    {


    }


}


         


PublicclassB:

A


{


    Publicstaticvoid Main ()


    {


        B B1 = newB ();


        B1.M1
();


        //Error, Cannot access private member M2


        //B1.M2 ();


    }


}


Method Hiding and
Inheritance We will look at an example of how to hide a method in C#.
The Parent class has a write () method which is available to the child class.
In the child class I have cre
ated a new
write () method. So, now if I create an instance of child class and call the
write () method, the child class write () method will be called. The child
class is hiding the base class write () method. This is called method hiding.



If we want to call the parent class write () method, we would have to type cast
the child object to Parent type and then call the write () method as shown in
the code snippet below.


Using System;


PublicclassParent


{


    Publicvoid Write ()


    {


        Console.WriteLine ("Parent
Class write method"
);


    }


}


 


PublicclassChild:
Parent


{


    Publicnewvoid Write ()


    {


        Console.WriteLine ("Child
Class write method"
);


    }


   


    Publicstaticvoid Main ()


    {


        Child C1 = newChild ();


        C1.Write
();


        //Type caste C1 to be of type Parent and call Write ()
method


        ((Parent) C1).Write ();


    }


}


Polymorphism:


When a message can be processed in
different ways is called polymorphism. Polymorphism means many forms.


 


Polymorphism is one of the
fundamental concepts of OOP.


 


Polymorphism provides
following features:
 


  • It allows you to invoke methods
    of derived class through base class reference during runtime.
  • It has the ability for classes
    to provide different implementations of methods that are called through
    the same name.

Polymorphism is of two
types:
 


  1. Compile time polymorphism/Overloading
  2. Runtime polymorphism/Overriding

Compile Time
Polymorphism


 


Compile time polymorphism is method
and operators overloading. It is also called early binding.


 


In method overloading method
performs the different task at the different input parameters.


 


Runtime Time Polymorphism


 


Runtime time polymorphism is done
using inheritance and virtual functions. Method overriding is called runtime
polymorphism. It is also called late binding.


 


When overriding a method, you
change the behavior of the method for the derived class.  Overloading

a method simply involves having another method with the same prototype.


 


Caution:Don't confused method overloading with method overriding,
they are different, unrelated concepts. But they sound similar.


 


Method overloading has nothing to do
with inheritance or virtual methods.


 


Following are examples of methods
having different overloads:


 


void area(int side);


void area(int l, int b);


void area(float radius);


 


Practical example of
Method Overloading (Compile Time Polymorphism)


 


using System;


 


namespacemethod_overloading


{


    classProgram


    {


       
publicclassPrint


       
{


           


           
publicvoid display(string
name)


     
      {


               
Console.WriteLine ("Your
name is : "
+ name);


           
}


 


           
publicvoid display(int
age, float marks)


           
{


               
Console.WriteLine ("Your
age is : "
+ age);


               
Console.WriteLine ("Your
marks are :"
+ marks);


           
}


       
}


       


       
staticvoid Main(string[]
args)


       
{


 


           
Printobj = newPrint ();


           
obj.display ("George");


           
obj.display (34, 76.50f);


           
Console.ReadLine ();


       
}


    }


}


 


Note:In the code if you observe display method is called two
times. Display method will work according to the number of parameters and type
of parameters.


 


When and why to use
method overloading


 


Use method overloading in situation
where you want a class to be able to do something, but there is more than one
possibility for what information is supplied to the method that carries out the
task.


 


You should consider overloading a
method when you for some reason need a couple of methods that take different
parameters, but conceptually do the same thing.


 


Method overloading showing many
forms.


 


using System;


 


namespacemethod_overloading_polymorphism


{


    ClassProgram


    {


       
PublicclassShape


       
{


           
Publicvoid Area (float
r)


     
      {


               
float a = (float)3.14
* r;


               
// here we have used function overload with 1
parameter.


               
Console.WriteLine ("Area
of a circle: {0}"
,a);


           
}


 


           
PublicvoidArea(float
l, float b)


        
   {


               
float x = (float)l*
b;


               
// here we have used function overload with 2
parameters.


               
Console.WriteLine ("Area
of a rectangle: {0}"
,x);


 


           
}


 


           
publicvoid Area(float
a, float b, float
c)


 
          {


               
float s = (float)(a*b*c)/2;


               
// here we have used function overload with 3
parameters.


               
Console.WriteLine ("Area
of a circle: {0}"
, s);


           
}


       
}


 


       
Staticvoid Main (string[]
args)


       
{


           
Shapeob = newShape ();


           
ob.Area(2.0f);


           
ob.Area(20.0f,30.0f);


           
ob.Area(2.0f,3.0f,4.0f);


           
Console.ReadLine ();


       
}


    }


}


 


Things to keep in mind while method
overloading


 


If you use overload for method,
there are couple of restrictions that the compiler imposes.


 


The rule is that overloads must be
different in their signature, which means the name and the number and type of
parameters.


 


There is no limit to how many
overload of a method you can have. You simply declare them in a class, just as
if they were different methods that happened to have the same name.


 


Constructors and
Destructors:


Classes have complicated internal
structures, including data and functions, object initialization and cleanup for
classes is much more complicated than it is for simple data structures.
Constructors and destructors are special member functions of classes that are
used to construct and destroy class objects. Construction may involve memory
allocation and initialization for objects. Destruction may involve cleanup and
deallocation of memory for objects.


  • Constructors and destructors do not have return types
    nor can they return values.
  • References and pointers cannot be used on constructors
    and destructors because their addresses cannot be taken.
  • Constructors cannot be declared with the keyword
    virtual.
  • Constructors and destructors cannot be declared static,
    const, or volatile.
  • Unions cannot contain class objects that have
    constructors or destructors.

Constructors and destructors obey
the same access rules as member functions. For example, if you declare a
constructor with protected access, only derived classes and friends can use it
to create class objects.


The compiler automatically calls
constructors when defining class objects and calls destructors when class
objects go out of scope. A constructor does not allocate memory for the class
object it’s this pointer refers to, but may allocate storage for more objects
than its class object refers to. If memory allocation is required for objects,
constructors can explicitly call the new operator. During cleanup, a destructor
may release objects allocated by the corresponding constructor. To release
objects, use the delete operator.


Example of Constructor


classC


{


      
privateint x;    


      
privateint y;


      
public C (int
i, int j)


      
{


                

x = i;


                
y = j;


      
}


 
     publicvoid
display ()     


      
{


              
Console.WriteLine(x + "i+" + y);


      
}


}

Example
of Destructor


classD


{


       
public D ()


       
{


           
// constructor


       
}         


       
~D ()


       
{


          
// Destructor


       
}


}


 


 


Interfaces







Interfaces, like
classes, define a set of properties, methods, and events. But unlike classes,
interfaces do not provide implementation. They are implemented by classes, and
defined as separate entities from classes. An interface represents a contract,
in that a class that implements an interface must implement every aspect of
that interface exactly as it is defined.


To define an interface:


interfaceabc



{


void xyz();


intthis[int index] { get; set; }


//event EventHandler E;


void F(int value);


string P { get; set; }


 



}


 


classProgram:abc



{


 


privatestring p1;


publicvoid F(int tot)


{


System.Console.WriteLine("Value:" + tot);


 


}


 


publicvoid xyz()


{


System.Console.WriteLine("In Demo :: xyz");


}


 


publicstring P


{


get


{


 


return p1;


}


set


{


 


value = p1;


 


}


}


 


publicintthis[int index]


{


get {


return 5;


}


set {


Console.WriteLine("this[{0}] = {1}", index, value);


}


}


staticvoid Main(string[] args)


{


System.Console.WriteLine("Hello Interfaces");


Program objpro = newProgram();


objpro.xyz();


objpro.F(100);


 


objpro.p1="PMP";


 


 


Console.WriteLine("MY FILED = {0}", objpro.p1 );


 


 


Console.WriteLine("a.MyProperty = {0}", objpro.P);


 


 


 


objpro[3] = objpro[1] = objpro[2];


 


Console.WriteLine("a[3] = {0}", objpro[3]);


 


 


Console.ReadKey();


 


}


 



}


 


Abstract class


Abstract classes, which declared with the abstract
keyword, cannot be instantiated. It can only be used as a super-class for other
classes that extend the abstract class. Abstract class is the concept and
implementation gets completed when it is being realized by a subclass. In
addition to this a class can inherit only from one abstract class (but a class
may implement many interfaces) and must override all its abstract methods/
properties and may override virtual methods/ properties.


abstractclassMotorcycle




{


//Any one can call this


publicvoidstartengine()


{


 


}


//only derived class can
call this


protectedvoidaddgas(int gallons)


{


 


 


}


//Derived class can
override the base class implementation


publicvirtualint Drive(int miles, int speed)


{


return 1;


 


 


}


//Derived Classes must
implement this


publicabstractdoubleGetTopSpeed();


 


 



}


 


classProgram:Motorcycle



{


 


// privateTer[] arr = new Ter[100];


 


 


publicoverridedoubleGetTopSpeed()


{


return 108.4;


 


}



}


staticvoid Main(string[] args)


{


 


Programmoto = newProgram();


 


 


moto.startengine();


moto.addgas(15);


moto.Drive(5, 20);


double Speed =
moto.GetTopSpeed();


stringstrspeed =
Speed.ToString();


Console.WriteLine("My Speed:");


Console.WriteLine(Speed);



}


 


Inheritance


Ability of a new class to be created, from an
existing class by extending it, is called inheritance.


Inheritance.gif


http://www.codeproject.com/images/minus.gifCollapse
|
Copy Code


public class Exception


{


}


 


 


public class IOException : Exception


{


}


According to the above example the new class
(IOException), which is called the derived class or subclass, inherits the
members of an existing class (Exception), which is called the base class or
super-class. The class IOException can extend the functionality of the class
Exception by adding new types and methods and by overriding existing ones.


4.17. What is Polymorphisms?


Polymorphisms is a generic term that means 'many
shapes'. More precisely Polymorphisms means the ability to request that the
same operations be performed by a wide range of different types of things.


At times, I used to think that understanding Object
Oriented Programming concepts have made it difficult since they have grouped
under four main concepts, while each concept is closely related with one
another. Hence one has to be extremely careful to correctly understand each
concept separately, while understanding the way each related with other
concepts.


In OOP the polymorphisms is achieved by using many
different techniques named method overloading, operator overloading and method
overriding,


4.18. What is Method
Overloading?


The method overloading is the ability to define
several methods all with the same name.


http://www.codeproject.com/images/minus.gifCollapse
|
Copy Code


public class MyLogger


{


public void LogError(Exception e)


{


//
Implementation goes here


}


 


publicboolLogError(Exception e, string message)


{


//
Implementation goes here


}


}


4.19. What is Operator Overloading?


The operator overloading (less commonly known as
ad-hoc polymorphisms) is a specific case of polymorphisms in which some or all
of operators like +, - or == are treated as polymorphic functions and as such
have different behaviors depending on the types of its arguments.


http://www.codeproject.com/images/minus.gifCollapse
|
Copy Code


public class Complex


{


privateint real;


publicint Real


{ get { return real; } }


 


privateint imaginary;


publicint Imaginary


{ get { return imaginary; } }


 


public Complex(int real, int imaginary)


{


this.real = real;


this.imaginary = imaginary;


}


 


public static Complex operator +(Complex c1, Complex
c2)


{


return new Complex(c1.Real + c2.Real, c1.Imaginary +
c2.Imaginary);


}


}


I above example I have overloaded the plus operator
for adding two complex numbers. There the two properties named Real and
Imaginary has been declared exposing only the required “get” method, while the
object’s constructor is demanding for mandatory real and imaginary values with
the user defined constructor of the class.


4.20. What is Method Overriding?


Method overriding is a language feature that allows
a subclass to override a specific implementation of a method that is already
provided by one of its super-classes.


A subclass can give its own definition of methods
but need to have the same signature as the method in its super-class. This
means that when overriding a method the subclass's method has to have the same
name and parameter list as the super-class's overridden method.


http://www.codeproject.com/images/minus.gifCollapse
|
Copy Code


using System;


public class Complex


{


privateint real;


publicint Real


{ get { return real; } }


 


privateint imaginary;


publicint Imaginary


{ get { return imaginary; } }


 


public Complex(int real, int imaginary)


{


this.real = real;


this.imaginary = imaginary;


}


 


public static Complex operator +(Complex c1, Complex
c2)


{


return new Complex(c1.Real + c2.Real, c1.Imaginary +
c2.Imaginary);


}


 


public override string ToString()


{


return (String.Format("{0} + {1}i", real,
imaginary));


}


}


In above example I have extended the implementation
of the sample Complex class given under operator overloading section. This
class has one overridden method named “ToString”, which override the default
implementation of the standard “ToString” method to support the correct string
conversion of a complex number.


 


Struct uses:


Both Visual Basic and C# also provide a light
version of classes called structures that
are useful when you need to create large array of objects and do not want to
consume too much memory for that.


structSampleStruct
{
}

 


//*******************************


structExforstruct



{


int a;


publicint value


{


get


{


return a;


}


set


{


 


a = value;


 


}


}


 


publicint b()


{


returnint.Parse(Console.ReadLine());


 


 


}


 


 



}


classstructex1



{


publicstaticvoid Main(String[] args)


{


 


Exforstruct ex = newExforstruct();


Console.WriteLine("enter a number:");


ex.value = ex.b();


 


Console.WriteLine("u en was{0} ", ex.value);


Console.ReadKey();


// return 0;


 


}


 


 



}


 


Delegates







A delegate is
a type that defines a method signature, and can provide a reference to any
method with a compatible signature. You can invoke (or call) the method through
the delegate. Delegates are used to pass methods as arguments to other methods.



NoteNote



Event handlers are nothing
more than methods that are invoked through delegates. For more information
about using delegates in event handling, see Events and Delegates.


To create a delegate:


publicdelegatevoidSampleDelegate(stringstr);

To create a reference to a method that matches the
signature specified by the delegate:


classSampleClass
{
// Method that matches the SampleDelegate signature.
publicstaticvoidsampleMethod(string message)
    {
// Add code here.
    }
// Method that instantiates the delegate.
voidSampleDelegate()
    {
SampleDelegatesd = sampleMethod;
sd("Sample string");
    }
}

Events (C# Programming
Guide)





Events enable a class
or object to notify other classes or objects when something of interest occurs.
The class that sends (or raises) the event is called the publisher and the
classes that receive (or handle) the event are called subscribers.


In a typical C# Windows
Forms or Web application, you subscribe to events raised by controls such as
buttons and list boxes. You can use the Visual C# integrated development
environment (IDE) to browse the events that a control publishes and select the
ones that you want to handle. The IDE automatically adds an empty event handler
method and the code to subscribe to the event. For more information, see
How to: Subscribe to and Unsubscribe from Events (C#
Programming Guide)
.


Events Overview







Events have the
following properties:


  • The publisher determines when an event is raised; the
    subscribers determine what action is taken in response to the event.
  • An event can have multiple subscribers. A subscriber
    can handle multiple events from multiple publishers.
  • Events that have no subscribers are never raised.
  • Events are typically used to signal user actions such
    as button clicks or menu selections in graphical user interfaces.
  • When an event has multiple subscribers, the event
    handlers are invoked synchronously when an event is raised. To invoke
    events asynchronously, see
    Calling Synchronous Methods Asynchronously.
  • Events can be used to synchronize threads.
  • In the .NET Framework class library, events are based
    on the
    EventHandler
    delegate and the
    EventArgs
    base class.

 


 


 


publicclassmydelgae



{


publicdelegatevoidLogHandler(string message);


 


publiceventLogHandler
log;


 


publicvoid Process()


{


Onlog("Process()
begin"
);


Onlog("Process()
end"
);


 


 


}


 


protectedvoidOnlog(string message)


{


 


if (log != null)


{


 


log(message);


 


 


}


}


 



}


publicclassFIlecreator



{


FileStreamfstream;


StreamWriterstreamwrite;


 


publicFIlecreator(stringmsg)


{


 


 


fstream = newFileStream(msg, FileMode.Create);


streamwrite = newStreamWriter(fstream);


 


 


}


publicvoid logger(stringmsgtext)


{


 


streamwrite.WriteLine(msgtext);


 


}


 


 


publicvoidcloseall()


{


streamwrite.Close();


fstream.Close();


 


 


}


 



}


classdelgatesample



{


staticvoid Logger(string s)


{


 


Console.WriteLine(s);


 


}


staticvoid Main(string[] args)


{


FIlecreator f1 = newFIlecreator("Process.log");


mydelgaemydel = newmydelgae();


 


mydel.log += newmydelgae.LogHandler(Logger);


 


mydel.log += newmydelgae.LogHandler(f1.logger);


 


mydel.Process();


 


f1.closeall();


Console.ReadKey();


 


 


 


 


}



}


 


Generics (C#
Programming Guide)


Visual Studio 2010


Generics were added to
version 2.0 of the C# language and the common language runtime (CLR). Generics
introduce to the .NET Framework the concept of type parameters, which make it
possible to design classes and methods that defer the specification of one or
more types until the class or method is declared and instantiated by client
code. For example, by using a generic type parameter T you can write a single
class that other client code can use without incurring the cost or risk of
runtime casts or boxing operations, as shown here:


 


// Declare the generic
class.


publicclassGenericList<T>


{


void Add(T input) { }


}


classTestGenericList


{


privateclassExampleClass { }


staticvoid Main()


{


// Declare a list of
type int.


GenericList<int> list1 = newGenericList<int>();


 


// Declare a list of
type string.


GenericList<string> list2 = newGenericList<string>();


 


// Declare a list of
type ExampleClass.


GenericList<ExampleClass>
list3 =
newGenericList<ExampleClass>();


}


}


 


 


Generics Overview









  • Use generic types to maximize code reuse, type safety,
    and performance.
  • The most common use of generics is to create collection
    classes.
  • The .NET Framework class library contains several new
    generic collection classes in the
    System.Collections.Generic namespace. These should be used whenever possible
    instead of classes such as
    ArrayList
    in the
    System.Collections namespace.
  • You can create your own generic interfaces, classes,
    methods, events and delegates.
  • Generic classes may be constrained to enable access to
    methods on particular data types.
  • Information on the types that are used in a generic
    data type may be obtained at run-time by using reflection.



 


using System;


usingSystem.Collections.Generic;


usingSystem.Linq;


usingSystem.Text;


 


namespaceAlloops


{


 


classgenclas<T>



{


public T Field;


 


 



}


classgenericsample



{


staticvoid Main(string[] args)


{


//GENERIC


//************************************************


genclas<string>gcls=newgenclas<string>()
;


gcls.Field = "PRABU";


gcls.Field = ".P";


 


Console.WriteLine("My Name is:= {0}", gcls.Field);


 


 


//************************************************


// LIST


 


 


//Represents a strongly
typed list of objects that can be accessed by index. Provides methods to
search,sort and manipulate list.


 


List<string>dynosars = newList<string>();


Console.WriteLine("Name:", dynosars.Capacity);


dynosars.Add("s1");


dynosars.Add("s2");


dynosars.Add("s3");


dynosars.Add("s4");


Console.WriteLine();


foreach (stringdynnameindynosars)


{


Console.WriteLine(dynname);


 


}


Console.WriteLine("\nCapacity: {0}", dynosars.Capacity);


Console.WriteLine("Count: {0}", dynosars.Count);


 


//************************************************


 


Console.ReadKey();


 


}



}


}


 


 


Related Sections


Boxing and Unboxing
(C# Programming Guide)


Boxing is the process of
converting a
value type to the type object or to any interface type implemented by
this value type. When the CLR boxes a value type, it wraps the value inside a
System.Object and stores it on the managed heap. Unboxing extracts the value
type from the object. Boxing is implicit; unboxing is explicit. The concept of
boxing and unboxing underlies the C# unified view of the type system, in which
a value of any type can be treated as an object.


In the following
example, the integer variable i is boxed and assigned to object o.


 


int i = 123;


// The following line
boxes i.


object o = i;


 


 


The object o can then be
unboxed and assigned to integer variable i:


Gallery


o = 123;


i = (int)o; // unboxing


 


 


The following examples
illustrate how boxing is used in C#.


// ToString example.


// ToString is a member
of the Object class. In each of the


// following examples, a
value is wrapped in an object instance


// so that ToString can
be called.


Console.WriteLine(123.ToString());


Console.WriteLine(true.ToString());


Console.WriteLine(3.415.ToString());


 


// You could do the
conversion explicitly, but boxing does it for


// you.


Console.WriteLine(((object)123).ToString());


 


 


// Hashtable exampleRe.presents
a collection of key/value pairs that are organized based on the hash code of
the key.


 


 


// using System.Collections;


Hashtable h = newHashtable();


 


 


 


// The signature for the
Add method in the Hashtable class is


// Add(object key,
object value). Boxing enables you to call the


// method easily with
arguments of many types.


h.Add(3.4, "three point four");


h.Add(true, 77);


 


// You could do the
conversion explicitly, but boxing does it


// for you.


h.Add((object)3.41, (object)"three point four");


 


 


// To verify that boxing
is taking place, first clear the hashtable.


// This time add
key/value pairs in which all the key arguments


// are integers and all
the value arguments are strings.


h.Clear();


h.Add(2, "two");


h.Add(3, "three");


h.Add(4, "four");


 


// Pull out the keys.


ICollectiontheKeys =
h.Keys;


 


// WriteLine accepts
many types of arguments, including both


// integers and objects.
In this example, each item is an object,


// so the loop displays
the keys without any problems.


foreach (var item intheKeys)


Console.WriteLine(item);


 


int product = 1;


// Operataor * does not
accept object arguments. To multiply the


// keys, you need to
unbox them.


foreach (var item intheKeys)


{


// The following line
causes a compiler error.


// product = product *
item;


// Unboxing is required.


product = product * (int)item;


}


// The product is 24.


Console.WriteLine(product);


 


// Output:


// 123


// True


// 3.415


// 123


// 4


// 3


// 2


// 24


 


Hastable


 


 


classHatablesample



{


publicstaticvoidPrintKeysAndValues(HashtablemyList)


{


IDictionaryEnumeratormyEnumerator
= myList.GetEnumerator();


Console.WriteLine("\t-KEY-\t-VALUE-");


while
(myEnumerator.MoveNext())


Console.WriteLine("\t{0}:\t{1}", myEnumerator.Key,
myEnumerator.Value);


Console.WriteLine();


}


 


staticvoid Main(string[] args)


{


//Hashtable h = new
Hashtable();


 


//h.Add(3.4, "Three
point four");


//h.Add(true, 77);


//// h.Add((object)3.4,(object)"Three point
Four");


////h.Clear();


////h.Add(2,
"two");


////h.Add(3,

"Three");


////h.Add(4,
"Four");


 


 


//ICollectiontheKeys =
h.Keys;


 


//foreach (var item in
theKeys)


// Console.WriteLine(item);


 


//int product = 1;


 


 


//foreach (var item in
theKeys)


//{


// // The following line causes a compiler
error.


// // product = product * item;


// // Unboxing is required.


// product = product * (int)item;


// Console.WriteLine(product);


//}


 


HashtablemyHT = newHashtable();


myHT.Add("First",
"Hello");


myHT.Add("Second",
"World");


myHT.Add("Third",
"!");


 


// Displays the
properties and values of the Hashtable.


Console.WriteLine("myHT");


Console.WriteLine(" Count: {0}", myHT.Count);


Console.WriteLine(" Keys and
Values:"
);


PrintKeysAndValues(myHT);


 


 


 


Console.ReadKey();


 


 


 


}


 


 


 


 



}


 


Iterators (C#
Programming Guide)





An iterator is a method,
getaccessor,
or operator that performs a custom iteration over an array or collection class
by using the
yield

keyword. The yield return statement causes an element in the source
sequence to be returned immediately to the caller before the next element in
the source sequence is accessed. Although you write an iterator as a method,
the compiler translates it into a nested class that is, in effect, a state
machine. This class keeps track of the position of the iterator as long the foreach
loop on the client code continues.



NoteNote



To see what the
compiler does behind the scenes, use the ILDASM.exe tool to view the
intermediate language (IL) code that is generated for an iterator method.


An iterator is invoked
from client code by using a
foreach
statement. For example, you can create an iterator for a class that returns the
elements in reverse order, or that performs an operation on each element before
the iterator returns it. When you create an iterator for your
class
or
struct,
you do not have to implement the whole
IEnumerator interface. When the compiler detects your iterator, it will
automatically generate the Current, MoveNext and Dispose methods of the
IEnumerator or IEnumerator<T> interface.


Iterators Overview









  • An iterator is a section of code that returns an
    ordered sequence of values of the same type.
  • An iterator can be used as the body of a method, an
    operator, or a getaccessor.
  • The iterator code uses the yield return
    statement to return each element in turn. yield break ends the
    iteration.
  • Multiple iterators can be implemented on a class. Each
    iterator must have a unique name just like any class member, and can be
    invoked by client code in a foreach statement as follows:
    foreach(int x in SampleClass.Iterator2){}.
  • The return type of an iterator must be IEnumerable,
    IEnumerator,
    IEnumerable<T>, or IEnumerator<T>.
  • Iterators are the basis for the deferred execution
    behavior in LINQ queries.



The yield
keyword is used to specify the value, or values, that are returned. When the yield
return
statement is reached, the current location is stored. Execution is
restarted from this location the next time that the iterator is called.


Iterators are especially
useful with collection classes, providing an easy way to iterate complex data
structures such as binary trees.


Example







In this example, the
DaysOfTheWeek class is a simple collection class that stores the days of the
week as strings. After each iteration of a
foreach
loop, the next string in the collection is returned.


publicclassDaysOfTheWeek : System.Collections.IEnumerable


{


string[] days = { "Sun",
"Mon", "Tue",
"Wed", "Thr",
"Fri", "Sat"

};


 


publicSystem.Collections.IEnumeratorGetEnumerator()


{


for (int i = 0; i

<days.Length; i++)


{


yieldreturn days[i];


}


}


}


 


classTestDaysOfTheWeek


{


staticvoid Main()


{


// Create an instance of
the collection class


DaysOfTheWeek week = newDaysOfTheWeek();


 


// Iterate with foreach


foreach (string day in week)


{


System.Console.Write(day
+
" ");


}


}


}


// Output: Sun Mon Tue
Wed Thr Fri Sat


 


 


Example1:


using System;


usingSystem.Collections.Generic;


usingSystem.Linq;


usingSystem.Text;


usingSystem.Collections;


namespaceAlloops


{


classiteratorsample



{


//ITERATOR


 


staticvoid Main()


{


 


Daysofweek DA = newDaysofweek();


 


// iteratorsample DA =new iteratorsample ();


 


foreach (stringstin DA)


{


Console.Write(st + " ");


 


}


Console.ReadKey();


 


}



}


}


 


 


using System;


usingSystem.Collections.Generic;


usingSystem.Linq;


usingSystem.Text;


 


namespaceAlloops


{


publicclassDaysofweek:System.Collections.IEnumerable



{


string[] days = { "Sun", "Mon",

"Tue", "Wed",
"Thr", "Fri",
"Sat" };


publicSystem.Collections.IEnumeratorGetEnumerator()


{


for (int i = 0; i <days.Length; i++)


{


yieldreturn days[i];


}


}


 




}


}


 


 


LINQ Query Expressions
(C# Programming Guide)


Language-Integrated
Query (LINQ) is the name for a set of technologies based on the integration of
query capabilities directly into the C# language (also in Visual Basic and
potentially any other .NET language). With LINQ, a query is now a first-class
language construct, just like classes, methods, events and so on.


For a developer who
writes queries, the most visible "language-integrated" part of LINQ
is the query expression. Query expressions are written in a declarative query
syntax introduced in C# 3.0. By using query syntax, you can perform even
complex filtering, ordering, and grouping operations on data sources with a
minimum of code. You use the same basic query expression patterns to query and
transform data in SQL databases, ADO.NET Datasets, XML documents and
streams, and .NET collections.


The following example
shows the complete query operation. The complete operation includes creating a
data source, defining the query expression, and executing the query in a foreach
statement.


 


 


classLINQQueryExpressions


{


staticvoid Main()


{


 


// Specify the data
source.


int[] scores = newint[] { 97, 92, 81, 60 };


 


// Define the query
expression.9


IEnumerable<int>scoreQuery =


from score in scores


where score > 80


select score;


 


// Execute the query.


foreach (int i inscoreQuery)


{


Console.Write(i + " ");


}


}


}


// Output: 97 92 81


 


 


For more information
about the basics of LINQ in C#, see
Getting Started with LINQ in C#.


How to: Write LINQ
Queries in C#


This topic shows the
three ways in which you can write a LINQ query in C#:


  1. Use query syntax.
  2. Use method syntax.
  3. Use a combination of query syntax and method syntax.

The following examples
demonstrate some simple LINQ queries by using each approach listed previously.
In general, the rule is to use (1) whenever possible, and use (2) and (3)
whenever necessary.



NoteNote


These queries operate
on simple in-memory collections; however, the basic syntax is identical to
that used in LINQ to SQL and LINQ to XML.



Example







Query Syntax


The recommended way to
write most queries is to use query syntax to create query expressions. The
following example shows three query expressions. The first query expression
demonstrates how to filter or restrict results by applying conditions with a where
clause. It returns all elements in the source sequence whose values are greater
than 7 or less than 3. The second expression demonstrates how to order the
returned results. The third expression demonstrates how to group results
according to a key. This query returns two groups based on the first letter of
the word.


 


// Query #1.


List<int> numbers = new List<int>() { 5, 4, 1, 3, 9,
8, 6, 7, 2, 0 };


 


// The query variable
can also be implicitly typed by using var


IEnumerable<int>filteringQuery =


fromnumin numbers


wherenum< 3 || num> 7


selectnum;


 


// Query #2.


IEnumerable<int>orderingQuery =


fromnumin numbers


wherenum< 3 || num> 7


orderbynumascending


selectnum;


 


// Query #3.


string[] groupingQuery = { "carrots", "cabbage", "broccoli", "beans", "barley" };


IEnumerable<IGrouping<char, string>>queryFoodGroups =


from item ingroupingQuery


group item by item[0];


 


 


Note that the type of
the queries is
IEnumerable<T>. All of these queries could be written using var as shown
in the following example:


var query = from num in
numbers...


In each previous
example, the queries do not actually execute until you iterate over the query
variable in a foreach statement. For more information, see
Introduction to LINQ Queries (C#).


 


 


Namespaces (C#
Programming Guide)


Namespaces are heavily
used in C# programming in two ways. First, the .NET Framework uses namespaces
to organize its many classes, as follows:


 


System.Console.WriteLine("Hello World!");


 


 


System is a namespace and Console is a class in
that namespace. The using keyword can be used so that the complete name
is not required, as in the following example:


using System;


 


 


Console.WriteLine("Hello");


Console.WriteLine("World!");


 


 


For more information,
see
using Directive (C# Reference).


Second, declaring your
own namespaces can help you control the scope of class and method names in
larger programming projects. Use the
namespace keyword to declare a namespace, as in the following example:


 


namespaceSampleNamespace


{


classSampleClass


{


publicvoidSampleMethod()


{


System.Console.WriteLine(


"SampleMethod
inside SampleNamespace"
);


}


}


}


 


 


Namespaces Overview







Namespaces have the
following properties:


  • They organize large code projects.
  • They are delimited by using the .operator.
  • The using directive obviates the requirement to
    specify the name of the namespace for every class.
  • The global namespace is the "root"
    namespace: global::System will always refer to the .NET Framework
    namespace System.

Constructors


Constructors are class methods that are executed
automatically when an object of a given type is created. Constructors usually
initialize the data members of the new object. A constructor can run only once
when a class is created
To define a constructor
for a class:


 


publicclassSampleClass
{
publicSampleClass()
    {
// Add code here
    }
}
 
 
 
Copy constructor

 


classTestconstruct



{


int A, B;


publicTestconstruct(int X, int Y)


{


 


A = X;


B = Y;


 


}


publicTestconstruct(Testconstruct
T)


{


 


A = T.A;


B = T.B;


 


}


publicvoid print()


{


 


Console.Write("A={0}\tB={1}", A, B);


 


}



}


classcopyconstruct



{


 


staticvoid Main()


{


Testconstruct text1 = newTestconstruct(50,100);


 


Testconstruct t1 = newTestconstruct(text1);


text1.print();


t1.print();


Console.ReadKey();


 


}



}


 
 
Static constructor

 


classtext1



{


 


/*


Static constructor called only once time


A constructor doesn’t have any return type
even void.


Within a class you can
create only one static constructor.*/


 


 


public text1()


{


Console.Write("Instance Constructor");


 


}


static text1()


{


 


Console.Write("Static Constructor");


 


}


 


 



}


 


classstaticconstruct



{


 


 


 


staticvoid Main()


{


text1 t1 = newtext1();


 


text1 t2 = newtext1();


 


 


Console.Read();


 


 


}


 



}


 


 


 

Destructors


Destructors are used to destruct instances of
classes. In the .NET Framework, the garbage collector automatically manages the
allocation and release of memory for the managed objects in your application
. However, you may still need destructors to clean up any
unmanaged resources that your application creates.
There can be only one destructor for a class.


Events


Events enable a class
or object to notify other classes or objects


when something of interest occurs. The class that sends (or raises) the event
is called the 
publisher and the classes that receive (or handle) the event are
called 
subscribers. For more information about events, how they are raised
and handled, see 
Handling and Raising Events.


Nested Classes


A class defined within another class is called nested. By default, the nested class is private.


class Container
{
class Nested
    {
// Add code here.
    }
}

To create an instance of the nested class, use the
name of the container class followed by the dot and then followed by the name
of the nested class:


Container.NestednestedInstance = newContainer.Nested()

Access
Modifiers and Access Levels


All classes and class members can specify what
access level they provide to other classes by using access modifiers.


The following access modifiers are available:



Visual Basic Modifier


C# Modifier


Definition


Public (Visual Basic)


public


The type or member can be accessed by any other
code in the same assembly or another assembly that references it.


Private (Visual Basic)


private


The type or member can only be accessed by code in
the same class.



Protected (Visual Basic)


protected



The type or member can only be accessed by code in
the same class or in a derived class.


Friend (Visual Basic)



internal


The type or member can be accessed by any code in
the same assembly, but not from another assembly.


Protected Friend


protected internal



The type or member can be accessed by any code in
the same assembly, or by any derived class in another assembly.


Static (Shared) Classes and Members


A static (shared in Visual Basic) member of the class is a
property, procedure, or field that is shared by all instances of a class.


To define a static (shared) member:


 


staticclassSampleClass
{
publicstaticstringSampleString = "Sample String";
}

To access the static (shared) member, use the name
of the class without creating an object of this class:


Console.WriteLine(SampleClass.SampleString);

Anonymous
Types


Anonymous types enable you to create objects
without writing a class definition for the data type. Instead, the compiler
generates a class for you. The class has no usable name and contains the
properties you specify in declaring the object.


To create an instance of an anonymous type:


// sampleObject is an instance of a simple anonymous type.
varsampleObject = 
new { FirstProperty = "A", SecondProperty = "B" };

 


Overriding
Members


By default, a derived class inherits all members
from its base class. If you want to change the behavior of the inherited
member, you need to override it. That is, you can define a new implementation
of the method, property or event in the derived class.


The following modifiers are used to control how
properties and methods are overridden:




Visual Basic Modifier


C# Modifier


Definition



Overridable (Visual Basic)


virtual (C# Reference)



Allows a class member to be overridden in a derived
class.


Overrides (Visual Basic)



override (C# Reference)


Overrides a virtual (overridable) member defined in
the base class.


NotOverridable (Visual Basic)


Not supported



Prevents a member from being overridden in an
inheriting class.


MustOverride (Visual Basic)



abstract (C# Reference)


Requires that a class member to be overridden in
the derived class.



Shadows (Visual Basic)


new Modifier (C# Reference)


Hides a member inherited from a base class



 


Destructors (C#
Programming Guide)





Destructors are used to
destruct instances of classes.


  • A destructor does not take modifiers or have
    parameters.

For example, the
following is a declaration of a destructor for the class Car:


 


 


 


class Car


{


~Car()
// destructor


{


// cleanup statements...


}


}


 


 


The destructor
implicitly calls
Finalize

on the base class of the object. Therefore, the previous destructor code is
implicitly translated to the following code:


Copy


protected override void
Finalize()


{


try


{


// Cleanup statements...


}


finally


{


base.Finalize();


}


}


This means that the
Finalize method is called recursively for all instances in the inheritance
chain, from the most-derived to the least-derived.


Indexers (C# Programming
Guide)


Indexers allow instances
of a class or struct to be indexed just like arrays. Indexers resemble
properties except that their accessors take parameters.


In the following example,
a generic class is defined and provided with simple
get
and
setaccessor
methods as a means of assigning and retrieving values. The Program class
creates an instance of this class for storing strings.


 


classSampleCollection<T>


{


// Declare an array to
store the data elements.


private T[] arr = new T[100];


 


// Define the indexer,
which will allow client code


// to use [] notation on
the class instance itself.


// (See line 2 of code
in Main below.)


public T this[int i]


{


get


{


// This indexer is very
simple, and just returns or sets


// the corresponding
element from the internal array.


returnarr[i];


}


set


{


arr[i] = value;


}


}


}


 


// This class shows how
client code uses the indexer.


class Program


{


staticvoid Main(string[] args)


{


// Declare an instance
of the SampleCollection type.


SampleCollection<string>stringCollection = newSampleCollection<string>();


 


// Use [] notation on
the type.


stringCollection[0] = "Hello, World";


System.Console.WriteLine(stringCollection[0]);


}


}


 


 


Indexers Overview









  • Indexers enable objects to be indexed in a similar
    manner to arrays.
  • A getaccessor returns a value. A setaccessor
    assigns a value.
  • The this
    keyword is used to define the indexers.
  • The value

    keyword is used to define the value being assigned by the set
    indexer.
  • Indexers do not have to be indexed by an integer value;
    it is up to you how to define the specific look-up mechanism.
  • Indexers can be overloaded.
  • Indexers can have more than one formal parameter, for
    example, when accessing a two-dimensional array.



 


interfaceabc



{


void xyz();


intthis[int index] { get; set; }


//event EventHandler E;


void F(int value);


string P { get; set; }


 



}


 


classProgram:abc



{


 


privatestring p1;


publicvoid F(int tot)


{


System.Console.WriteLine("Value:" + tot);


 


}


 


publicvoid xyz()


{


System.Console.WriteLine("In Demo :: xyz");


}


 


publicstring P


{


get


{


 


return p1;


}


set


{


 


value = p1;


 


}


}


 


publicintthis[int index]


{


get {


return 5;


}


set {


Console.WriteLine("this[{0}] = {1}", index, value);


}


}


staticvoid Main(string[] args)


{


System.Console.WriteLine("Hello Interfaces");


Program objpro = newProgram();


objpro.xyz();


objpro.F(100);


 


objpro.p1="PMP";


 


 


Console.WriteLine("MY FILED = {0}", objpro.p1 );


 


 


Console.WriteLine("a.MyProperty = {0}", objpro.P);


 


 


 


objpro[3] = objpro[1] = objpro[2];


 


Console.WriteLine("a[3] = {0}", objpro[3]);


 


 


Console.ReadKey();


 


}


 



}


 


Partial Classes and Methods (C#
Programming Guide)


Visual Studio 2010


Other Versions


 


It is possible to split the definition of a class or a struct, an interface or a method over two or more source files. Each source file
contains a section of the type or method definition, and all parts are combined
when the application is compiled.


Partial Classes







There are several situations when splitting a
class definition is desirable:


·        
When working on large
projects, spreading a class over separate files enables multiple programmers to
work on it at the same time.


·        
When working with
automatically generated source, code can be added to the class without having
to recreate the source file. Visual Studio uses this approach when it creates
Windows Forms, Web service wrapper code, and so on. You can create code that
uses these classes without having to modify the file created by Visual Studio.


·        
To split a class
definition, use the 
partial keyword modifier, as shown here:


 
publicpartialclass Employee
{
publicvoidDoWork()
    {
    }
}
 
publicpartialclass Employee
{
publicvoidGoToLunch()
    {
    }
}
 
 

The partial keyword
indicates that other parts of the class, struct, or interface can be defined in
the namespace. All the parts must use the partial keyword.
All the parts must be available at compile time to form the final type. All the
parts must have the same accessibility, such aspublic, private, and
so on.


If any part is declared abstract, then the whole
type is considered abstract. If any part is declared sealed, then the whole
type is considered sealed. If any part declares a base type, then the whole
type inherits that class.


All the parts that specify a base class must
agree, but parts that omit a base class still inherit the base type. Parts can
specify different base interfaces, and the final type implements all the
interfaces listed by all the partial declarations. Any class, struct, or
interface members declared in a partial definition are available to all the
other parts. The final type is the combination of all the parts at compile
time.



NoteNote



The partial modifier is not available on
delegate or enumeration declarations.


The following example shows that nested types can
be partial, even if the type they are nested within is not partial itself.


 
class Container
{
partialclass Nested
    {
void Test() { }
    }
partialclass Nested
    {
void Test2() { }
    }
}
 
 

At compile time, attributes of partial-type
definitions are merged. For example, consider the following declarations:


 
[SerializableAttribute]
partialclass Moon { }
 
[ObsoleteAttribute]
partialclass Moon { }
 
 

They are equivalent to the following declarations:


 
[SerializableAttribute]
[ObsoleteAttribute]
class Moon { }
 
 

The following are merged from all the partial-type
definitions:


·        
XML comments


·        

interfaces


·        
generic-type parameter
attributes


·        
class attributes


·        
members


For example, consider the following declarations:


 
partialclass Earth : Planet, IRotate { }
partialclass Earth : IRevolve { }
 
 

They are equivalent to the following declarations:


class Earth : Planet, IRotate, IRevolve { }
 

sealed (C# Reference)


Visual
Studio 2005


Other Versions


http://i3.msdn.microsoft.com/Areas/Brand/Content/Msdn_ImageSprite.png


19 out of 39 rated this helpful - Rate this topic


The sealed modifier can be applied to classes, instance
methods and properties. A sealed class cannot be inherited. A sealed method
overrides a method in a base class, but itself cannot be overridden further in
any derived class. When applied to a method or property, the sealed

modifier must always be used with override (C# Reference).


Use the sealed modifier in a class declaration to prevent
inheritance of the class, as in this example:


 
sealed class SealedClass
{
publicint x; 
publicint y;
}

It is an error to use a sealed class as a base class or to use the abstract modifier with a
sealed class.


Structs are implicitly sealed; therefore, they cannot be inherited.


For more information about inheritance, see Inheritance (C# Programming Guide).


Example






// cs_sealed_keyword.cs
using System;
sealed class SealedClass
{
publicint x;
publicint y;
}
 
classMainClass
{
static void Main()
    {
SealedClasssc = new SealedClass();
sc.x = 110;
sc.y = 150;
Console.WriteLine("x = {0}, y = {1}", sc.x, sc.y);
    }
}

Output







 


x = 110, y = 150

In the preceding example, if you attempt to inherit from the sealed class by
using a statement like this:


classMyDerivedC: SealedClass {} //
Error


you will get the error message:


'MyDerivedC' cannot inherit from sealed
class 'SealedClass'.


unsafe (C# Reference)


Visual
Studio 2005


Other Versions


http://i3.msdn.microsoft.com/Areas/Brand/Content/Msdn_ImageSprite.png


7 out of 11 rated this helpful - Rate this topic


The unsafe keyword denotes an unsafe context, which is
required for any operation involving pointers. For more information, see Unsafe Code and Pointers (C#
Programming Guide)
.


You can use the unsafe modifier in the declaration of a
type or a member. The entire textual extent of the type or member is therefore
considered an unsafe context. For example, the following is a method declared
with the unsafe modifier:


 
unsafe static void FastCopy(byte[] src, byte[] dst, int count)
{
    // Unsafe context: can use pointers here.
}

The scope of the unsafe context extends from the parameter list to the end
of the method, so pointers can also be used in the parameter list:


 
unsafe static void FastCopy ( byte* ps, byte* pd, int count ) {...}

You can also use an unsafe block to enable the use of an unsafe code inside
this block. For example:


 
unsafe
{
    // Unsafe context: can use pointers here.
}

To compile unsafe code, you must specify the /unsafe compiler option.
Unsafe code is not verifiable by the common language runtime.


Example






// cs_unsafe_keyword.cs
// compile with: /unsafe
using System;
classUnsafeTest
{
   // Unsafe method: takes pointer to int:
unsafe static void SquarePtrParam(int* p)
   {
      *p *= *p;
   }
 
unsafe static void Main()
   {
int i = 5;
      // Unsafe method: uses address-of operator (&):
SquarePtrParam(&i);
Console.WriteLine(i);
   }
}

Output



 

25

 


volatile (C# Reference)


Visual
Studio 2005


Other Versions


http://i3.msdn.microsoft.com/Areas/Brand/Content/Msdn_ImageSprite.png


4 out of 30 rated this helpful - Rate this topic


The volatile keyword indicates that a field might be
modified by multiple concurrently executing threads. Fields that are declared volatile
are not subject to compiler optimizations that assume access by a single
thread. This ensures that the most up-to-date value is present in the field at
all times.


The volatile modifier is usually used for a field that is
accessed by multiple threads without using the lock Statement (C# Reference)

statement to serialize access. See How to: Create and Terminate Threads
(C# Programming Guide)
for an example of volatile
in a multi-threaded scenario.


The volatile keyword can be applied to fields of these
types:


·        

Reference types.


·        
Pointer types (in an unsafe context). Note that
while the pointer itself can be volatile, the object that it points to cannot.
In other words, you cannot declare a "pointer to volatile."


·        
Integral types such as sbyte, byte, short,
ushort, int, uint, char, float, and bool.


·        
An enum type with an integral base type.


·        
Generic type parameters known to be reference
types.


·        
IntPtr and UIntPtr.


The volatile keyword can only be applied to fields of a class or struct.
Local variables cannot be declared volatile.


Example






The following example shows how to declare a public field variable as volatile.


// csharp_volatile.cs
// compile with: /target:library
class Test
{
public volatile int i;
 
Test(int _i)
   {
      i = _i;
   }
}

extern (C# Reference)


Visual
Studio 2005


Other Versions


http://i3.msdn.microsoft.com/Areas/Brand/Content/Msdn_ImageSprite.png


21 out of 27 rated this helpful - Rate this topic


The extern modifier is used to declare a method that is
implemented externally. A common use of the extern modifier is
with the DllImport attribute when using Interop services to
call into unmanaged code; in this case, the method must also be declared as static,
as shown in the following example:


[DllImport("avifil32.dll")]
private static extern void AVIFileInit();


NoteNote


The extern keyword also can define an external assembly
alias, making it possible to reference different versions of the same
component from within a single assembly. For more information, see extern alias (C# Reference).


It is an error to use the abstract (C# Reference) and extern
modifiers together to modify the same member. Using the extern
modifier means that the method is implemented outside the C# code, while using
the abstract modifier means that the method implementation is
not provided in the class.



NoteNote


The extern keyword is more limited in use than in C++. To
compare with the C++ keyword, see Using extern to Specify Linkage

in the C++ Language Reference.


Example






In this example, the program receives a string from the user and displays it
inside a message box. The program uses the MessageBox
method imported from the User32.dll
library.


using System;
usingSystem.Runtime.InteropServices;
classMainClass
{
   [DllImport("User32.dll")]
public static extern intMessageBox(int h, string m, string c, int type);
 
staticint Main() 
   {
stringmyString; 
Console.Write("Enter your message: ");
myString = Console.ReadLine();
returnMessageBox(0, myString, "My Message Box", 0);
   }
}

This example creates a DLL from a C program that is invoked from within the
C# program in the next example.


// cmdll.c
// compile with: /LD
int __declspec(dllexport) SampleMethod(int i)
{
return i*10;
}

This example uses two files, CM.cs
and Cmdll.c, to demonstrate extern.
The C file is the external DLL created in Example 2 that is invoked from within
the C# program.


// cm.cs
using System;
usingSystem.Runtime.InteropServices;
public class MainClass
{
   [DllImport("Cmdll.dll")]
public static extern intSampleMethod(int x);
 
static void Main() 
   {
Console.WriteLine("SampleMethod() returns {0}.", SampleMethod(5));
   }
}

Output



 

SampleMethod() returns 50.

 


readonly (C# Reference)


Visual
Studio 2005


Other Versions


http://i3.msdn.microsoft.com/Areas/Brand/Content/Msdn_ImageSprite.png


20 out of 27 rated this helpful - Rate this topic


The readonly keyword is a modifier that you can use on
fields. When a field declaration includes a readonly modifier,
assignments to the fields introduced by the declaration can only occur as part
of the declaration or in a constructor in the same class. In this example, the
value of the field year
cannot be changed in the method ChangeYear,
even though it is assigned a value in the class constructor:


class Age
{
readonlyint _year;
Age(int year)
    {
        _year = year;
    }
voidChangeYear()
    {
        _year = 1967; // Will not compile.
    }
}

Remarks






You can assign a value to a readonly field only in the
following contexts:


·        

When the variable is initialized in the
declaration, for example:


·         public readonlyint y = 5;

·        
For an instance field, in the instance
constructors of the class that contains the field declaration, or for a static
field, in the static constructor of the class that contains the field
declaration. These are also the only contexts in which it is valid to pass a readonly field as an out or ref parameter.



NoteNote



The readonly keyword is different from the const keyword. A const
field can only be initialized at the declaration of the field. A readonly
field can be initialized either at the declaration or in a constructor.
Therefore, readonly fields can have different values
depending on the constructor used. Also, while a const field
is a compile-time constant, the readonly field can be used
for runtime constants as in the following example:



NoteNote


public static readonlyuint l1 = (uint)DateTime.Now.Ticks;


Example






// cs_readonly_keyword.cs
// Readonly fields
using System;
public class ReadOnlyTest
{
classSampleClass
   {
publicint x;
      // Initialize a readonly field
publicreadonlyint y = 25;
publicreadonlyint z;
 
publicSampleClass()
      {
         // Initialize a readonly instance field
         z = 24;
      }
 
publicSampleClass(int p1, int p2, int p3)
      {
         x = p1;
         y = p2;
         z = p3;
      }
   }
 
static void Main()
   {
SampleClass p1 = new SampleClass(11, 21, 32);   // OK
Console.WriteLine("p1: x={0}, y={1}, z={2}", p1.x, p1.y, p1.z);
SampleClass p2 = new SampleClass();
      p2.x = 55;   // OK
Console.WriteLine("p2: x={0}, y={1}, z={2}", p2.x, p2.y, p2.z);
   }
}

Output



 

p1: x=11, y=21, z=32
p2: x=55, y=25, z=24

Modifiers (C# Reference)


Visual
Studio 2005


Other Versions


http://i3.msdn.microsoft.com/Areas/Brand/Content/Msdn_ImageSprite.png


5 out of 9 rated this helpful - Rate this topic


Modifiers are used to modify declarations of types and type members. This
section introduces the C# modifiers:



Modifier



Purpose


Access Modifiers


·        
public

·        
private

·        
internal


·        
protected


Specify the declared accessibility of types and type members.


abstract


Indicates that a class is intended only to be a base class of other
classes.


const


Specify Specifies that the value of the field or the local variable cannot
be modified.


event


Declares an event.


extern


Indicates that the method is implemented externally.


·        
new


Hides an inherited member from a base class member.



override


Provides a new implementation of a virtual member inherited from a base
class.



partial


Defines partial classes and structs throughout the same assembly.



readonly


Declares a field that can only be assigned values as part of the
declaration or in a constructor in the same class.



sealed


Specifies that a class cannot be inherited.



static


Declares a member that belongs to the type itself rather than to a
specific object.



unsafe


Declares an unsafe context.



virtual


Declares a method or an accessor whose implementation can be changed by an
overriding member in a derived class.



volatile


Indicates that a field can be modified in the program by something such as
the operating system, the hardware, or a concurrently executing thread.



C# Keywords


Visual
Studio 2005


Other Versions


http://i3.msdn.microsoft.com/Areas/Brand/Content/Msdn_ImageSprite.png


80 out of 175 rated this helpful - Rate this topic


Keywords are predefined reserved identifiers that have special meanings to
the compiler. They cannot be used as identifiers in your program unless they
include @ as a prefix. For
example, @if is a legal
identifier but if is not
because it is a keyword.



abstract


event



new


struct



as


explicit


null



switch


base



extern


object



this


bool



false


operator


throw



break


finally



out


true


byte


fixed



override


try



case


float


params



typeof


catch



for


private



uint


char



foreach


protected


ulong



checked


goto



public


unchecked


class


if



readonly


unsafe



const


implicit


ref



ushort


continue



in


return



using


decimal



int


sbyte


virtual



default


interface



sealed


volatile


delegate


internal



short


void



do


is


sizeof



while


double



lock


stackalloc



 


else



long


static


 


enum


namespace


string


 


Contextual Keywords







get



partial


set


value


 


Arrays (C# Programming Guide)


Visual
Studio 2005


Other Versions


http://i3.msdn.microsoft.com/Areas/Brand/Content/Msdn_ImageSprite.png


82 out of 133 rated this helpful - Rate this topic


An array is a data structure that contains a number of variables of the same
type. Arrays are declared with a type:


type[] arrayName;


The following examples create single-dimensional, multidimensional, and
jagged arrays:


C#


classTestArraysClass
{
staticvoid Main()
    {
// Declare a single-dimensional array 
int[] array1 = newint[5];
 
// Declare and set array element values
int[] array2 = newint[] { 1, 3, 5, 7, 9 };
 
// Alternative syntax
int[] array3 = { 1, 2, 3, 4, 5, 6 };
 
// Declare a two dimensional array
int[,] multiDimensionalArray1 = newint[2, 3];
 
// Declare and set array element values
int[,] multiDimensionalArray2 = { { 1, 2, 3 }, { 4, 5, 6 } };
 
// Declare a jagged array
int[][] jaggedArray = newint[6][];
 
// Set the values of the first array in the jagged array structure
jaggedArray[0] = newint[4] { 1, 2, 3, 4 };
    }
}
 

Array Overview


An array has the following properties:


·        
An array can be Single-Dimensional, Multidimensional or Jagged.


·        
The default value of numeric array elements are
set to zero, and reference elements are set to null.


·        
A jagged array is an array of arrays, and
therefore its elements are reference types and are initialized to null.


·        
Arrays are zero indexed: an array with n elements is indexed from 0 to n-1.


·        
Array elements can be of any type, including an
array type.


·        
Array types are reference types derived from
the abstract base type Array. Since this type
implements IEnumerable and IEnumerable, you can use foreach iteration on all
arrays in C#.


Strings (C# Programming Guide)


Visual
Studio 2005


Other Versions


http://i3.msdn.microsoft.com/Areas/Brand/Content/Msdn_ImageSprite.png


7 out of 12 rated this helpful - Rate this topic


The following sections discuss the string data type, which
is an alias for the String class.


In This Section


Using Strings (C# Programming Guide)


How to: Parse Strings Using the Split
Method (C# Programming Guide)


How to: Search Strings Using String
Methods (C# Programming Guide)


How to: Search Strings Using Regular
Expressions (C# Programming Guide)


How to: Join Multiple Strings (C#
Programming Guide)


How to: Modify String Contents (C#
Programming Guide)


 


Using Strings (C# Programming Guide)


Visual
Studio 2005


Other Versions


http://i3.msdn.microsoft.com/Areas/Brand/Content/Msdn_ImageSprite.png


61 out of 82 rated this helpful - Rate this topic


A C# string is an array of characters declared using the string
keyword. A string literal is declared using quotation marks, as shown in the
following example:


C#


string s = "Hello, World!";
 

You can extract substrings, and concatenate strings, like this:


C#


string s1 = "orange";
string s2 = "red";
 
s1 += s2;
System.Console.WriteLine(s1);  // outputs "orangered"
 
s1 = s1.Substring(2, 5);
System.Console.WriteLine(s1);  // outputs "anger"
 

String objects are immutable, meaning that they cannot be changed
once they have been created. Methods that act on strings actually return new
string objects. In the previous example, when the contents of s1 and s2 are concatenated to form a single string, the two
strings containing "orange"
and "red" are both
unmodified. The += operator creates a new string that contains
the combined contents. The result is that s1

now refers to a different string altogether. A string containing just "orange" still exists, but is
no longer referenced when s1
is concatenated.



NoteNote



Use caution when creating references to strings. If you create a reference
to a string, and then "modify" the string, the reference will
continue to point to the original object, not the new object that was created
when the string was modified. The following code illustrates the danger:


string s1 = "Hello";
string s2 = s1;
s1 += " and goodbye.";
Console.WriteLine(s2); //outputs "Hello"

Because modifications to strings involve the creation of new string objects,
for performance reasons, large amounts of concatenation or other involved
string manipulation should be performed with the StringBuilder class, like
this:


C#


System.Text.StringBuildersb = newSystem.Text.StringBuilder();
sb.Append("one ");
sb.Append("two ");
sb.Append("three");
stringstr = sb.ToString();
 

The StringBuilder class is discussed further in the
"Using Stringbuilder" section.


Working with Strings


Escape Characters


Escape characters such as "\n" (new line) and "\t" (tab)
can be included in strings. The line:


C#


string hello = "Hello\nWorld!";
 

is the same as:


Hello


World!


If you want to include a backward slash, it must be preceded with another
backward slash. The following string:


Casting (C# Programming Guide)


Visual
Studio 2005


Other Versions


http://i3.msdn.microsoft.com/Areas/Brand/Content/Msdn_ImageSprite.png


28 out of 71 rated this helpful - Rate this topic


Converting between data types can be done explicitly using a cast, but in
some cases, implicit conversions are allowed. For example:


C#


staticvoidTestCasting()
{
int i = 10;
float f = 0;
    f = i;  // An implicit conversion, no data will be lost.
    f = 0.5F;
    i = (int)f;  // An explicit conversion. Information will be lost.
}
 

A cast explicitly invokes the conversion operator from one type to another.
The cast will fail if no such conversion operator is defined. You can write
custom conversion operators to convert between user-defined types. For more
information about defining a conversion operator, see explicit (C# Reference) and implicit (C# Reference).


Example






The following program casts a double to an int. The program will not
compile without the cast.


C#


class Test
{
staticvoid Main()
    {
double x = 1234.7;
int a;
        a = (int)x;  // cast double to int
System.Console.WriteLine(a);
    }
}
 

Output






1234


Exception Handling (C# Programming Guide)


Visual Studio 2010


Other
Versions


http://i3.msdn.microsoft.com/Areas/Brand/Content/Msdn_ImageSprite.png


2 out of 3
rated this helpful
 - Rate this topic


A try block
is used by C# programmers to partition code that might be affected by an
exception. Associated
 catch blocks
are used to handle any resulting exceptions. A
 finally block
contains code that is run regardless of whether or not an exception is thrown
in the
 try block, such as releasing resources that
are allocated in the
 try block. A try block requires one or more associated catch blocks, or a finally block, or both.


The following examples show a try-catch statement, a try-finally statement, and a try-catch-finally statement.


C#


 
try
{
// Code to try goes here.
}
catch (SomeSpecificException ex)
{
// Code to handle the exception goes here.
// Only catch exceptions that you know how to handle.
// Never catch base class System.Exception without
// rethrowing it at the end of the catch block.
}
 
 

C#


 
try
{
// Code to try goes here.
}
finally
{
// Code to execute after the try block goes here.
}
 
 

C#


 
try
{
// Code to try goes here.
}
catch (SomeSpecificException ex)
{
// Code to handle the exception goes here.
}
finally
{
// Code to execute after the try (and possibly catch) blocks 
// goes here.
}
 
 

A try block
without a
 catch or finally block causes a compiler error.


Catch Blocks







A catch block
can specify the type of exception to catch. The type specification is called an
 exception filter. The
exception type should be derived from
Exception. In general, do not specify Exception as the
exception filter unless either you know how to handle all exceptions that might
be thrown in the
 try block, or you have included a throw statement
at the end of your
 catch block.


Multiple catch blocks with different exception filters
can be chained together. The
 catch blocks are evaluated from top to bottom in
your code, but only onecatch
 block is executed for each exception that
is thrown. The first
 catch block that specifies the exact type or a
base class of the thrown exception is executed. If no
 catch block specifies a matching exception
filter, a
 catch block
that does not have a filter is selected, if one is present in the statement. It
is important to position
 catch blocks with the most specific (that is,
the most derived) exception types first.


You should catch exceptions when the following conditions are
true:


·        
You have a good understanding of why the exception might be thrown,
and you can implement a specific recovery, such as prompting the user to enter
a new file name when you catch a
 FileNotFoundException object.


·        
You can create and throw a new, more specific exception.


C#


 
intGetInt(int[] array, int index)
{
try
    {
return array[index];
    }
catch(System.IndexOutOfRangeException e)
    {
thrownewSystem.ArgumentOutOfRangeException(
"Parameter index is out of range.");
    }
}
 
 

·        
You want to partially handle an exception before passing it on for
additional handling. In the following example, a
 catch block is used to add an entry to an error
log before re-throwing the exception.


C#


 
try
{
// Try to access a resource.
}
catch (System.UnauthorizedAccessException e)
{
// Call a custom error logging procedure.
LogError(e);
// Re-throw the error.
throw;     
}
 
 

Finally Blocks







A finally block
enables you to clean up actions that are performed in a
 try block. If present, the finally block executes last, after the try block and any matchedcatch block. A finally block always runs, regardless of whether
an exception is thrown or a
 catch block matching the exception type is
found.


The finally block can be used to release resources
such as file streams, database connections, and graphics handles without
waiting for the garbage collector in the runtime to finalize the objects. See
 using Statement (C# Reference) for more information.


In the following example, the finally block is used to close a file that is
opened in the
 try block.
Notice that the state of the file handle is checked before the file is closed.
If the
 try block cannot open the file, the file
handle still has the value
 null and the finally block does not try to close it.
Alternatively, if the file is opened successfully in the
 try block, the finally block closes the open file.


C#


 
System.IO.FileStream file = null;
System.IO.FileInfofileinfo = newSystem.IO.FileInfo("C:\\file.txt");
try
{
file = fileinfo.OpenWrite();
file.WriteByte(0xF);
}
finally
{
// Check for null because OpenWrite might have failed.
if (file != null)
    {
file.Close();
    }
}
 


What is Lambda Expression? A simple guide For beginners



Whenever we talk about
LINQ then everything related to LINQ comes as a part of discussion and so the
Lambda Expressions are. Sometimes people ask the question about the Lambda
Expression; It look so weird why should I use it in my code and what exactly it
stands for? Developers who either from C++ or working on C# 2.0 are still not
have clear vision of Lambda Expression. What are Lambda Expressions?, When
& Where to use them? These are the basic question that can comes in mind
when anybody heard of new programming things.

Through this post I'll try to answer these question. There are new terms are
being introduced with every release of .Net framework so lets get started with
Lambda Expression for now: 



What is Lambda Expression?


Lambda expressions are similar to anonymous methods introduced in C# 2.0,
except that lambda expressions are more concise and more flexible. All lambda
expressions use the lambda operator =>, which is read as “goes to”. The left
side of the lambda operator specifies the input parameters and the right side
holds the expression or statement block. 



Lets take an example:


delegate int anonymousDel(int i);

            
anonymousDel myDelegate = new anonymousDel(


            
delegate(int x)

            {

                
return x * 2;

            });



            
Console.WriteLine("{0}",
myDelegate(5));




The segment inside the braces of anonymousDel is the also called as Anonymous
Function. 

Now lets convert it to Lambda Expression: 


anonymousDel myDelegate = x => x * 2;




x => x * 2 is the Expression that is known as Lambda Expression. All lambda
expressions use the lambda operator =>, which is read as "goes
to". The left side of the lambda operator specifies the input parameters
(if any) and the right side holds the expression or statement block. The lambda
expression x => x * 2 is read "x goes to 2 times x." This reduced
the no. of line as you can see and the output is still the same. 




The above expression can be generalize for clear understanding. 

(input parameters) => Expression; 

and can be termed as "Expression Lambdas" since
single Expression is involved here.
 

A Lambda Expression can contain multiple statements and
can be surrounded by { } just like anonymous functions.
 

(input param1, input param2) => { statement1,
Statement 2};
 


For e.g. 


anonymousDel2 getBigInteger = (x, y) => { if (x > y) return x; else returny; };


Console.WriteLine(getBigInteger(10,15));




You can raise a question here how x & y are being
treated as integer while you didn't declared them as integer?
 

Here is the answer, When writing lambdas, you often do not
have to specify a type for the input parameters because the compiler can infer
the type based on the lambda body, the underlying delegate type, and other
factors as described in the C# Language Specification.
 

Anonymous function that take no parameter and return
nothing can be written in form of Lambda Expression like below:


delegate void doSomething();


            
doSomething IamVoid = () => { Console.WriteLine("Hello
there! I take nothing and return nothing"
); };

            
//call the Anonymous function

           
IamVoid();




When & Where to use Lambda Expression?


Whenever you came to know about new term and you already
know what it is then directly ask yourself when & where it would be used.
The Lambda Expressions can be used to  simply replacing the Anonymous
functions, In the LINQ query methods, or any where you need to intialize
Generic delegates.


LINQ Query example:



LINQ to Objects


int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

            
int oddNumbers = numbers.Count(n => n % 2 == 1);




LINQ to SQL


Customers.Where(c
=> c.City == 
"London");




LINQ To XML


var xml1 = element.Descendants("customer").Where(cust
=> cust.Attribute(
"id").Value == CustomerId).SingleOrDefault();




OTHER

Func<>, Action<> and Expression<> are
the new generic delgates where you can use Lambda Expressions. Don't panic with
these new terms Lets take example where are these new generic delegates can be
used.




Look at the below code snippet:


delegate int anonymousDel2(int a, int b);


anonymousDel2 getBigInteger = (x, y) => { if (x > y) return x; else returny; };

Console.WriteLine(getBigInteger(10,15));




Lets modify the above code snippet using generic delegates
and Lambda Expressions


Func<int, int, int>
getBigInteger = (x, y) => { 
if (x > y) return x; elsereturn y; };


            
Console.WriteLine(getBigInteger(10,15));




Explanation of Func<int, int, int> would be Func<parameter1,
parameter2, returntype>


you can pass any number of argument but last mentioned
type would be the type of returned value. Similary we use Action<param1,
param2> in this we don't need to return any value. It denotes the Generic
delegate here that have return type void. These delegates are introduced to
provide the taste of Functional Progamming in the C# itself. if you are still
interested in further reading then its worth for me writing this post.
 




When to use Lambda
Expression?


Use whenever you feel reducing your line of code. Keep in
mind the code maintainability while reducing the number of code lines. People
think Lambda Expression as awkward looking code, But I'm telling you its worth
using them in code wisely and once you understood the concept you'll fall in
love using them. If you are going to use Excess of LINQ in your code then
Lambda Expression will be your favorite buddy helping you wrap your code logic
in few lines or may be Inline.




Hope you enjoyed reading this. Thanks for you time please
leave comment for any question/suggestion.


 

Partial Classes and Methods (C#
Programming Guide)


Visual Studio 2010


Other Versions


 


It is possible to split the definition of a class or a struct, an interface or a method over two or more source files. Each source file
contains a section of the type or method definition, and all parts are combined
when the application is compiled.


Partial Classes







There are several situations when splitting a
class definition is desirable:


·        
When working on large
projects, spreading a class over separate files enables multiple programmers to
work on it at the same time.


·        
When working with
automatically generated source, code can be added to the class without having
to recreate the source file. Visual Studio uses this approach when it creates
Windows Forms, Web service wrapper code, and so on. You can create code that
uses these classes without having to modify the file created by Visual Studio.


·        
To split a class
definition, use the 
partial keyword modifier, as shown here:


 
public partial class Employee
{
    public void DoWork()
    {
    }
}
 
public partial class Employee
{
    public void GoToLunch()
    {
    }
}
 
 

The partial keyword
indicates that other parts of the class, struct, or interface can be defined in
the namespace. All the parts must use the partial keyword.
All the parts must be available at compile time to form the final type. All the
parts must have the same accessibility, such aspublic, private, and
so on.


If any part is declared abstract, then the whole
type is considered abstract. If any part is declared sealed, then the whole
type is considered sealed. If any part declares a base type, then the whole
type inherits that class.


All the parts that specify a base class must
agree, but parts that omit a base class still inherit the base type. Parts can
specify different base interfaces, and the final type implements all the
interfaces listed by all the partial declarations. Any class, struct, or
interface members declared in a partial definition are available to all the
other parts. The final type is the combination of all the parts at compile
time.



NoteNote



The partial modifier is not available on
delegate or enumeration declarations.


The following example shows that nested types can
be partial, even if the type they are nested within is not partial itself.


 
class Container
{
    partial class Nested
    {
        void Test() { }
    }
    partial class Nested
    {
        void Test2() { }
    }
}
 
 

At compile time, attributes of partial-type
definitions are merged. For example, consider the following declarations:


 
[SerializableAttribute]
partial class Moon { }
 
[ObsoleteAttribute]
partial class Moon { }
 
 

They are equivalent to the following declarations:


 
[SerializableAttribute]
[ObsoleteAttribute]
class Moon { }
 
 

The following are merged from all the partial-type
definitions:


·        
XML comments


·        
interfaces


·        
generic-type parameter
attributes


·        
class attributes


·        

members


For example, consider the following declarations:


 
partial class Earth : Planet, IRotate { }
partial class Earth : IRevolve { }
 
 

They are equivalent to the following declarations:


class Earth : Planet, IRotate, IRevolve { }
 
 

Restrictions


There are several rules to follow when you are
working with partial class definitions:


·        

All partial-type
definitions meant to be parts of the same type must be modified withpartial. For example, the following class declarations
generate an error:


 
public partial class A { }
//public class tcA { }  // Error, must also be marked partial
 
 

·        
The partial modifier can only appear immediately
before the keywords class, struct, orinterface.


·        
Nested partial types
are allowed in partial-type definitions as illustrated in the following
example:


partial class ClassWithNestedClass
{
    partial class NestedClass { }
}
 
partial class ClassWithNestedClass
{
    partial class NestedClass { }
}
 
 

·        
All partial-type
definitions meant to be parts of the same type must be defined in the same
assembly and the same module (.exe or .dll file). Partial definitions cannot
span multiple modules.


·        
The class name and
generic-type parameters must match on all partial-type definitions. Generic
types can be partial. Each partial declaration must use the same parameter
names in the same order.


·        
The following keywords
on a partial-type definition are optional, but if present on one partial-type
definition, cannot conflict with the keywords specified on another partial
definition for the same type:


·        

public


·        
private


·        
protected


·        
internal


·        
abstract


·        
sealed


·        
base class


·        

new modifier (nested parts)


·        
generic constraints


For more information,
see 
Constraints on Type Parameters (C#
Programming Guide)
.


Example 1







Description


In the following example, the fields and the
constructor of the class, CoOrds, are declared in one partial class definition, and the
member, PrintCoOrds,
is declared in another partial class definition.


Code


public partial class CoOrds
{
    private int x;
    private int y;
 
    public CoOrds(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
}
 
public partial class CoOrds
{
    public void PrintCoOrds()
    {
        Console.WriteLine("CoOrds: {0},{1}", x, y);
    }
 
}
 
class TestCoOrds
{
    static void Main()
    {
        CoOrds myCoOrds = new CoOrds(10, 15);
        myCoOrds.PrintCoOrds();
 
        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
// Output: CoOrds: 10,15
 
 

Example 2







Description


The following example shows that you can also
develop partial structs and interfaces.


Code


 
partial interface ITest
{
    void Interface_Test();
}
 
partial interface ITest
{
    void Interface_Test2();
}
 
partial struct S1
{
    void Struct_Test() { }
}
 
partial struct S1
{
    void Struct_Test2() { }
}
 
 

Partial Methods







A partial class or struct may contain a partial
method. One part of the class contains the signature of the method. An optional
implementation may be defined in the same part or another part. If the
implementation is not supplied, then the method and all calls to the method are
removed at compile time.


Partial methods enable the implementer of one part
of a class to define a method, similar to an event. The implementer of the
other part of the class can decide whether to implement the method or not. If
the method is not implemented, then the compiler removes the method signature
and all calls to the method. The calls to the method, including any results
that would occur from evaluation of arguments in the calls, have no effect at
run time. Therefore, any code in the partial class can freely use a partial
method, even if the implementation is not supplied. No compile-time or run-time
errors will result if the method is called but not implemented.


Partial methods are especially useful as a way to
customize generated code. They allow for a method name and signature to be
reserved, so that generated code can call the method but the developer can
decide whether to implement the method. Much like partial classes, partial
methods enable code created by a code generator and code created by a human
developer to work together without run-time costs.


A partial method declaration consists of two
parts: the definition, and the implementation. These may be in separate parts
of a partial class, or in the same part. If there is no implementation
declaration, then the compiler optimizes away both the defining declaration and
all calls to the method.


Copy


// Definition in file1.cs
partial void onNameChanged();
 
// Implementation in file2.cs
partial void onNameChanged()
{
  // method body
}

·        
Partial method
declarations must begin with the contextual keyword 
partial and the method must return void.


·        
Partial methods can
have 
ref but not out parameters.


·        
Partial methods are
implicitly 
private, and therefore they cannot be virtual.


·        
Partial methods cannot
be 
extern, because the presence of the body determines whether they
are defining or implementing.


·        
Partial methods can
have 
static and unsafe modifiers.


·        
Partial methods can be
generic. Constraints are put on the defining partial method declaration, and
may optionally be repeated on the implementing one. Parameter and type parameter
names do not have to be the same in the implementing declaration as in the
defining one.


·        
You can make a delegate to a partial method that has been defined and implemented,
but not to a partial method that has only been defined.


 


 


1 What ‘s satellite assembly..?


 


A assembly containg localized resources for another assembly


2.       What
is delegate…?


A strongly typed function pointer…


3.       What is Boxing in .Net..?


Encapsulating a copy of a value type
in object.


 


 


Server.Transfer


Is used to post a form to another
page..Response.Redirect is used to redirect the user to another page.


What is round trip..?


 


Self post back


Command type object…?


Stored procedure..table direct,
text.


 


View state values
are stored in hidden fields.


Control state cannot be disabled.


 


Boxing…?


 


A reference Type to Value Type.


 


Repeater is Fastest Control


 


 


 


 


 


 







The official goal of the LINQ family of technologies is to add "general purpose query facilities to the .NET Framework that apply to all sources of information, not just relational or XML data".

 

20-11.jpg 

 

Advantages of LINQ

  1. LINQ offers an object-based, language-integrated way to query over data no matter where that data came from. So through  LINQ we can query database, XML as well as collections. 
  2. Compile time syntax checking
  3. It allows you to query collections like arrays, enumerable classes etc in the native language of your application, like VB or C# in much the same way as you would query a database using SQL

LINQ to Object

 

LINQ to Object provides functionality to query in-memory objects and collections. Any class that implements the IEnumerable<T> interface (in the System.Collections.Generic namespace) can be queried with SQO.

 

LINQ to ADO.NET

 

LINQ to ADO.NET deals with data from external sources, basically anything ADO.NET can connect to. Any class that implements IEnumerable<T> or IQueryable<T> (in the System.Query namespace) can be queried with SQO.  

  • LINQ to SQL (DLinq) {Queries performed against the relation database only Microsoft SQL Server Supported} 
  • LINQ to DataSet {Supports queries by using ADO.NET data sets and data tables} 
  • LINQ to Entities 

LINQ to XML (XLinq)

 

LINQ to XML is used to query XML data sources.

 

Here is a detailed tutorial on LINQ with C# for beginners. 

 

LINQ Code Examples

 

Here is a simple example that creates a array of integers. A LINQ query is used to return a var that stores the collection of returned data. Learn more: The var keyword in C#.

  1. int[] nums = new int[] {0,1,2};  
  2. var res = from a in nums where a < 3 orderby a select a;  
  3. foreach(int i in res)   
  4.  Console.WriteLine(i);

Let's look at a working example. Create a Web page or UI with a GridView control that we will use to display some data. The following code example defines a class, patient with some properties such as name, gender, age, and area.

  1. public class patient  
  2. {  
  3.       public patient()  
  4.        {  
  5.        }  
  6.        // Fields  
  7.         private string _name;  
  8.         private int _age;  
  9.         private string _gender;  
  10.         private string _area;  
  11.         // Properties  
  12.         public string PatientName  
  13.         {  
  14.             get { return _name; }  
  15.             set { _name = value; }  
  16.        }  
  17.          public string Area  
  18.         {  
  19.             get { return _area; }  
  20.             set { _area = value; }  
  21.         }  
  22.         public String Gender  
  23.         {  
  24.             get { return _gender; }  
  25.             set { _gender = value; }  
  26.         }  
  27.         public int Age  
  28.         {  
  29.             get { return _age; }  
  30.             set { _age = value; }  
  31.         }  
  32. }

Now, on the Web Page (ASP.NET Web Forms in this case), we create a List object dynamically. This program adds a single record but you an add a collection of records. Once the collection is ready, LINQ can be used to query the collection. 

 

In this code, a recorded is queired using LINQ and displayed in a GridView control.

 

Main Program

  1. using System.Collections.Generic;  
  2. public partial class _Default : System.Web.UI.Page   
  3. {  
  4.     protected void Page_Load(object sender, EventArgs e)  
  5.     {  
  6.         List<patient> pat=new List<patient>();  
  7.         patient p=new patient();  
  8.         p.patientname="Deepak dwij";  
  9.         p.patientstate = "UP";  
  10.         p.patientage = "25";  
  11.         p.patientcity = "Noida";  
  12.         pat.Add(p);  
  13.         GridView1.DataSource = from a in pat select a;  
  14.         GridView1.DataBind();    
  15.         //GridView1.DataSource = from pa in patients  
  16.                                    //where pa.Gender == "Male"  
  17.                                    //orderby pa.PatientName, pa.Gender, pa.Age  
  18.                                    //select pa;  
  19.         //GridView1.DataBind();       
  20.     }  
  21. }

The following code uses the selection operator type, which brings all those records whose age is more than 20 years.

  1. var mypatient = from pa in patients  
  2.                   where pa.Age > 20  
  3.                   orderby pa.PatientName, pa.Gender, pa.Age  
  4.                   select pa;  
  5.         foreach(var pp in mypatient)  
  6.         {  
  7.         Debug.WriteLine(pp.PatientName + " "+ pp.Age + " " + pp.Gender);  
  8.         }   

The following code snippet uses the grouping operator type that group patient data on the bases area.

  1. var op = from pa in patients  
  2.             group pa by pa.Area into g  
  3.             select new {area = g.Key, count = g.Count(), allpatient = g};  
  4.     foreach(var g in op)  
  5.      {  
  6.       Debug.WriteLine(g.count+ "," + g.area);  
  7.        foreach(var l in g.allpatient)  
  8.         {  
  9.          Debug.WriteLine("\t"+l.PatientName);  
  10.         }  
  11.      }  
  1. int patientCount = (from pa in patients  
  2.                     where pa.Age > 20  
  3.                     orderby pa.PatientName, pa.Gender, pa.Age   
  4.                    select pa).Count();  

Linq Example

Simple select

  1. int[] numbers = { 5, 4, 1, 3, 9, 8};  
  2. var numsPlusOne =from n in numbers select n;  
  3. foreach (var i in numsPlusOne)  
  4. {  
  5.     MessageBox.Show(i.ToString() );  
  6. }  

Multiple select

  1. int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };  
  2. int[] numbersB = { 1, 3, 5, 7, 8 };  
  3. var pairs =from a in numbersA from b in numbersB where a < b select new { a, b };  
  4. Console.WriteLine("Pairs where a < b:");  
  5. foreach (var pair in pairs)  
  6. {  
  7.     Console.WriteLine("{0} is less than {1}", pair.a, pair.b);  
  8. }  

Order by

  1. string[] words = { "cherry", "apple", "blueberry" };  
  2. var sortedWords =from w in words orderby w select w;  
  3. Console.WriteLine("The sorted list of words:");  
  4. foreach (var w in sortedWords)  
  5. {  
  6.     Console.WriteLine(w);  
  7. }  

Count function

  1. int[] factorsOf300 = { 2, 2, 3, 5, 5 };  
  2. int uniqueFactors = factorsOf300.Distinct().Count();  
  3. Console.WriteLine("There are {0} unique factors of 300.", uniqueFactors);  

OR

  1. int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
  2. int oddNumbers = numbers.Count(n => n % 2 == 1);
  3. Console.WriteLine("There are {0} odd numbers in the list.", oddNumbers);

C# Abstract Class

 

An abstract class is an incomplete class or special class we can't be instantiated. The purpose of an abstract class is to provide a blueprint for derived classes and set some rules what the derived classes must implement when they inherit an abstract class.

 

We can use an abstract class as a base class and all derived classes must implement abstract definitions. An abstract method must be implemented in all non-abstract classes using the override keyword. After overriding the abstract method is in the non-Abstract class. We can derive this class in another class and again we can override the same abstract method with it.

 

C# Abstract Class Features

  1. An abstract class can inherit from a class and one or more interfaces.
  2. An abstract class can implement code with non-Abstract methods.
  3. An Abstract class can have modifiers for methods, properties etc.
  4. An Abstract class can have constants and fields.
  5. An abstract class can implement a property.
  6. An abstract class can have constructors or destructors.
  7. An abstract class cannot be inherited from by structures.
  8. An abstract class cannot support multiple inheritance.

Example 1

  1. #region  
  2.   
  3. //An abstract calss can inherit from a class and one or more interfaces.  
  4.   
  5. interface IVendorTransDetails  
  6. {  
  7.     void getVendorID();  
  8. }  
  9. interface IClaimsTracker  
  10. {  
  11.     void getSeqID();  
  12. }  
  13. class ClaimsMaster  
  14. {  
  15.     string getDCNNO()  
  16.     {  
  17.         return "PC20100308A00005";  
  18.     }  
  19. }  

Example 2

  1. abstract class Abstract : ClaimsMaster, IClaimsTracker, IVendorTransDetails  
  2. {  
  3.     //Here we should implement modifiers oterwise it throws complie-time error  
  4.     public void getVendorID()  
  5.     {  
  6.         int s = new int();  
  7.         s = 001;  
  8.         Console.Write(s);  
  9.     }  
  10.   
  11.     public void getSeqID()  
  12.     {  
  13.         int SeqID = new int();  
  14.         SeqID = 001;  
  15.         Console.Write(SeqID);  
  16.     }  
  17. }   
  18. #endregion  

Example 3

 

  1.     #region  
  2.   
  3.     //An abstract class can implement code with non-Abstract methods.  
  4.   
  5. abstract class NonAbstractMethod  
  6. {  
  7.     //It is a Non-abstract method we should implement code into the non-abstract method on the class.   
  8.     public string getDcn()  
  9.     {  
  10.         return "PS20100301A0012";  
  11.     }   
  12.     public abstract void getSeqID();   
  13. }   
  14. class Utilize : NonAbstractMethod  
  15. {  
  16.     public override void getSeqID()  
  17.     {  
  18.     }  
  19.   
  20. }   
  21. #endregion  

Example 4

  1. #region   
  2. //Abstract class can have modifiers for methods,properties and An abstract class can implement a property  
  3.   
  4. public abstract class abstractModifier  
  5. {  
  6.     private int id;   
  7.     public int ID  
  8.     {  
  9.         get { return id; }  
  10.         set { id = value; }  
  11.     }   
  12.     internal abstract void Add();  
  13. }   
  14. #endregion  

Example 5

  1. #region   
  2. //Abstract class can have constant and fields  
  3. public abstract class ConstantFields  
  4. {  
  5.     public int no;  
  6.     private const int id = 10;  
  7. }  
  8. #endregion

Example 6

  1. #region   
  2. //An abstract class can have constructors or destructors  
  3. abstract class ConsDes  
  4. {  
  5.     ConsDes()  
  6.     {  
  7.     }  
  8.     ~ConsDes()  
  9.     {  
  10.     }  
  11. }  
  12. #endregion  

Example 7

  1. #region   
  2. //An abstract class cannot be inherited from by structures  
  3. public struct test  
  4. {  
  5. }  
  6. //We can't inheritance the struct class on the abstract class  
  7. abstract class NotInheritanceStruct  
  8. {  
  9. }  
  10. #endregion  

Example 8

  1. #region   
  2. //An abstract class cannot support multiple inheritance  
  3. class A  
  4. {  
  5. }  
  6. class B : A  
  7. {  
  8. }  
  9. abstract class Container : B //But we can't iherit like this : A,B  
  10. {  
  11. }  
  12. #endregion  

 

Theoretically there are basically 5 differences between Abstract Class and Interface which are listed as below:

 

1. A class can implement any number of interfaces but a subclass can at most use only one abstract class.

 

2. An abstract class can have non-abstract Methods(concrete methods) while in case of Interface all the methods has to be abstract.

 

3. An abstract class can declare or use any variables while an interface is not allowed to do so.

 

So following code will not compile

  1. interface TestInterface  
  2. {  
  3.     int x = 4;  // Filed Declaration in Interface  
  4.     void getMethod();  
  5.     string getName();  
  6. }  
  7.   
  8. abstract class TestAbstractClass  
  9. {  
  10.     int i = 4;  
  11.     int k = 3;  
  12.     public abstract void getClassName();  
  13. }  

It will generate a compile time error as

 

Error 1 Interfaces cannot contain fields.

 

So we need to omit Field Declaration in order to compile the code properly.

  1. interface TestInterface  
  2. {  
  3.     void getMethod();  
  4.     string getName();  
  5. }   
  6.   
  7. abstract class TestAbstractClass  
  8. {  
  9.     int i = 4;  
  10.     int k = 3;  
  11.     public abstract void getClassName();  
  12. }  

Above code compiles properly as no field declaration is there in Interface.

 

4. An abstract class can have constructor declaration while an interface can not do so.

 

So following code will not compile

  1. interface TestInterface  
  2. {  
  3.     // Constructor Declaration  
  4.     public TestInterface()  
  5.     {  
  6.     }  
  7.     void getMethod();  
  8.     string getName();  
  9. }  
  10.   
  11. abstract class TestAbstractClass  
  12. {  
  13.     public TestAbstractClass()  
  14.     {  
  15.     }  
  16.     int i = 4;  
  17.     int k = 3;  
  18.     public abstract void getClassName();  
  19. }  

Above code will generate a compile time error as

 

Error 1 Interfaces cannot contain constructors

 

So we need to omit constructor declaration from interface in order to compile our code.

 

Following code compile s perfectly

  1. interface TestInterface  
  2. {  
  3.     void getMethod();  
  4.     string getName();  
  5. }  
  6.   
  7. abstract class TestAbstractClass  
  8. {  
  9.     public TestAbstractClass()  
  10.     {  
  11.     }  
  12.     int i = 4;  
  13.     int k = 3;  
  14.     public abstract void getClassName();  
  15. }  

5. An abstract Class is allowed to have all access modifiers for all of its member declaration while in interface we can not declare any access modifier(including public) as all the members of interface are implicitly public.

 

Note here I am talking about the access specifiers of the member of interface and not about the interface.

 

Following code will explain it better

 

It is perfectly legal to give provide access specifier as Public (Remember only public is allowed)

  1. public interface TestInterface  
  2. {  
  3.     void getMethod();  
  4.     string getName();  
  5. }  

Above code compiles perfectly.

 

It is not allowed to give any access specifier to the members of the Interface.

  1. interface TestInterface  
  2. {  
  3.     public void getMethod();  
  4.     public string getName();  
  5. }  

Above code will generate a compile time error as

 

Error 1 The modifier 'public' is not valid for this item.

 

But the best way of declaring Interface will be to avoid access specifier on interface as well as members of interface.

  1. interface Test  
  2. {  
  3.     void getMethod();  
  4.     string getName();  
  5. }

 

 

4 comments:

  1. https://www.c-sharpcorner.com/UploadFile/dacca2/understand-formcollection-in-mvc-controller/

    ReplyDelete
  2. Better MVC URL http://www.binaryintellect.net/articles/4a00a9ce-73e5-4d89-aaae-2d835eca0854.aspx

    ReplyDelete
  3. http://www.altafkhatri.com/Technical/How-to-get-Ilist-value-from-ASP-net-mvc-postback/Bind-list-to-ASP-NET-MVC-object/Postback-object-list-binding

    ReplyDelete
  4. https://www.tutorialspoint.com/asp.net_mvc/asp.net_mvc_databases.htm

    ReplyDelete

.Net References