OOPS PART2

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.

Collapse | 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.
Collapse | 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.
Collapse | 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.
Collapse | 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.
Note
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
{
void Add(T input) { }
}
classTestGenericList
{
privateclassExampleClass { }
staticvoid Main()
{
// Declare a list of type int.
GenericList list1 = newGenericList();
 
// Declare a list of type string.
GenericList list2 = newGenericList();
 
// Declare a list of type ExampleClass.
GenericList list3 = newGenericList();
}
}
 
 
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
{
public T Field;
 
 
}
classgenericsample
{
staticvoid Main(string[] args)
{
//GENERIC
//************************************************
genclasgcls=newgenclas() ;
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.
 
Listdynosars = newList();
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.
Note
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 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, or IEnumerator.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 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#:
Use query syntax.Use method syntax.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.
Note
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 numbers = new List() { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
 
// The query variable can also be implicitly typed by using var
IEnumerablefilteringQuery =
fromnumin numbers
wherenum< 3 || num> 7
selectnum;
 
// Query #2.
IEnumerableorderingQuery =
fromnumin numbers
wherenum< 3 || num> 7
orderbynumascending
selectnum;
 
// Query #3.
string[] groupingQuery = { "carrots", "cabbage", "broccoli", "beans", "barley" };
IEnumerable>queryFoodGroups =
from item ingroupingQuery
group item by item[0];
 
 
Note that the type of the queries is IEnumerable. 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 createdTo 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
{
// 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.
SampleCollectionstringCollection = newSampleCollection();
 
// 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.
Note
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

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

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

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

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();
Note
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.
Note
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

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.
Note
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:
Note
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

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

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

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

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

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

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

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 fromException. 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 getBigInteger = (x, y) => { if (x > y) return x; elsereturn y; };
            Console.WriteLine(getBigInteger(10,15));

Explanation of Func would be Func
you can pass any number of argument but last mentioned type would be the type of returned value. Similary we use Action 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.
Note
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
 
 
 
 
 
 

No comments:

Post a Comment

.Net References