Oops baasics Part2



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


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.




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

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

}

}

}

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.

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.

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.

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

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.

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

}

}

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.

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

}

}

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

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

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.


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

}

}

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)

It is possible to split the definition of a class or astruct, 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.

sealed (C# Reference)

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, thesealed 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

unsafe (C# Reference)

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)

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 thelock Statement (C# Reference) statement to serialize access. SeeHow 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.

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

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

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 anout or ref parameter.



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

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


Modifier


Purpose


Access Modifiers


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.



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

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

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:

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

Strings (C# Programming Guide)

Visual Studio 2005

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

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

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, seeexplicit (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)

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<int, int, int> getBigInteger = (x, y) => { if (x > y) return x; elsereturn y; };


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



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

1. What is a Delegate in C#?

 

Delegate is one of the base types in .NET. Delegate is a class, which is used to create and invoke delegates at runtime.

 

C# Delegates

 

A delegate in C# is similar to a function pointer in C or C++. It's a new type of object in C#. Delegate is very special type of object as earlier the entire the object we used to defined contained data but delegate just contains the details of a method.

 

2. Why do we need delegates in C#?

 

Programmers often needs to pass a method as a parameter of other methods. For this purpose we create and use delegates.

A delegate is a class that encapsulates a method signature. Although it can be used in any context, it often serves as the basis for the event-handling model in C# and .NET.

 

One good way of understanding delegates is by thinking of a delegate as something that gives a name to a method signature.

 

Example:

  1. public delegate int DelegateMethod(int x, int y);  

Any method that matches the delegate's signature, which consists of the return type and parameters, can be assigned to the delegate.

 

This makes is possible to programmatically change method calls, and also plug new code into existing classes. As long as you know the delegate's signature, you can assign your own-delegated method.

 

This ability to refer to a method as a parameter makes delegates ideal for defining callback methods.

 

Delegate magic

 

In class we create its object, which is instance, but in delegate when we create instance that is also referred as delegate (means whatever you do you will get delegate).

 

Delegate does not know or care about the class of the object that it references. Any object will do; all that matters is that the method's argument types and return type match the delegate's. This makes delegates perfectly suited for "anonymous" invocation.

 

3. What are the benefits of delegates?

 

In simple words delegates are object oriented and type-safe and very secure as they ensure that the signature of the method being called is correct. Delegates makes event handling simple and easy.

 

4. What are types of delegates in C#?

 

There are two types of delegates, singlecast delegates, and multiplecast delegates.

 

Singlecast delegate

 

Singlecast delegate point to single method at a time. In this the delegate is assigned to a single method at a time. They are derived from System.Delegate class.

 

Multicast Delegate

 

When a delegate is wrapped with more than one method that is known as a multicast delegate.

 

In C#, delegates are multicast, which means that they can point to more than one function at a time. They are derived from System.MulticastDelegate class.

 

5. How to define a delegates in C#?

 

 

There are three steps in defining and using delegates:

 

1. Declaration

 

To create a delegate, you use the delegate keyword.

  1. [attributes] [modifiers] delegate ReturnType Name ([formal-parameters]);  
  • The attributes factor can be a normal C# attribute.
  • The modifier can be one or an appropriate combination of the following keywords: new, public, private, protected, or internal.
  •  The ReturnType can be any of the data types we have used so far. It can also be a type void or the name of a class.
  •  The Name must be a valid C# name. 

Because a delegate is a definituon for a method, you must use parentheses, required for every method. If this method will not take any argument, leave the parentheses empty.

 

Example:

  1. public delegate void DelegateExample();  

The above code is how a delegate with no papameters is defined.

 

2. Instantiation

  1. DelegateExample d1 = new DelegateExample(Display);  

The above code shows how a delegate is initiated.

 

3. Invocation 

  1. d1();  

The above code piece invokes a delegate d1().

 

6. What is a Singlecast delegate in C#?

 

Here is a sample code that demonstrates how to create and use a singlecast delegate.

  1. using System;    
  2. namespace ConsoleApplication5    
  3. {    
  4. class Program    
  5. {    
  6. public delegate void delmethod();    
  7.   
  8. public class P    
  9. {  
  10.   
  11. public static void display()    
  12. {    
  13. Console.WriteLine("Hello!");    
  14. }    
  15.   
  16. public static void show()    
  17. {    
  18. Console.WriteLine("Hi!");    
  19. }    
  20.   
  21. public void print()
  22. {
  23. Console.WriteLine("Print");
  24. }
  25.  
  26. }
  27.   
  28. static void Main(string[] args)
  29. {
  30. // here we have assigned static method show() of class P to delegate delmethod()
  31. delmethod del1 = P.show;
  32.   
  33. // here we have assigned static method display() of class P to delegate delmethod() using new operator
  34. // you can use both ways to assign the delagate
  35. delmethod del2 = new delmethod(P.display);
  36. P obj = new P();
  37.   
  38. // here first we have create instance of class P and assigned the method print() to the delegate i.e. delegate with class    
  39. delmethod del3 = obj.print;
  40.   
  41. del1();
  42. del2();
  43. del3();
  44. Console.ReadLine();
  45. }
  46. }
  47. }

7. What is a Multicast delegate in C#?

 

Here is sample code that demonstrates how to create and use a multicast delegate.

  1. using System;  
  2. namespace delegate_Example4  
  3. {  
  4.   
  5. class Program  
  6. {  
  7. public delegate void delmethod(int x, int y);  
  8.   
  9. public class TestMultipleDelegate  
  10. {  
  11. public void plus_Method1(int x, int y)  
  12. {  
  13. Console.Write("You are in plus_Method");  
  14. Console.WriteLine(x + y);  
  15. }  
  16.   
  17. public void subtract_Method2(int x, int y)  
  18. {  
  19. Console.Write("You are in subtract_Method");  
  20. Console.WriteLine(x - y);  
  21. }  
  22. }  
  23.   
  24. static void Main(string[] args)  
  25. {  
  26.   
  27. TestMultipleDelegate obj = new TestMultipleDelegate();  
  28. delmethod del = new delmethod(obj.plus_Method1);  
  29.   
  30. // Here we have multicast  
  31. del += new delmethod(obj.subtract_Method2);  
  32. // plus_Method1 and subtract_Method2 are called  
  33. del(50, 10);  
  34. Console.WriteLine();  
  35. //Here again we have multicast  
  36. del -= new delmethod(obj.plus_Method1);  
  37. //Only subtract_Method2 is called  
  38. del(20, 10);  
  39. Console.ReadLine();  
  40. }  
  41. }  
  42. }  

Point to remember about Delegates:

  • Delegates are similar to C++ function pointers, but are type safe.
  • Delegate gives a name to a method signature.
  • Delegates allow methods to be passed as parameters.
  • Delegates can be used to define callback methods.
  • Delegates can be chained together; for example, multiple methods can be called on a single event.
  • C# version 2.0 introduces the concept of Anonymous Methods, which permit code blocks to be passed as parameters in place of a separately defined method.
  • Delegate helps in code optimization.
  • Usage areas of delegates

The most common example of using delegates is in events. 

  • They are extensively used in threading
  • Delegates are also used for generic class libraries, which have generic functionality, defined.

 

8. What are Anonymous Delegates in C#?

 

You can create a delegate, but there is no need to declare the method associated with it. You do not have to explicitly define a method prior to using the delegate. Such a method is referred to as anonymous. In other words, if a delegate itself contains its method definition it is known as anonymous method.

 

The code is an example of using an anonymous delegate.

  1. using System;  
  2.   
  3. public delegate void Test();  
  4.   
  5. public class Program  
  6. {  
  7. static int Main()  
  8. {  
  9. Test Display = delegate()  
  10. {  
  11. Console.WriteLine("Anonymous Delegate method");  
  12. };  
  13.   
  14. Display();  
  15. return 0;  
  16. }  
  17. }  

Note: You can also handle event in anonymous method.

 

9. How Delegates are Related to Events in C#?

 

Events and delegate work together. An event is a reference to a delegate i.e. when an event is raised, a delegate is called. In C# terms, events are a special form of delegates. 

 

Events play an important part in user interfaces and programming notifications. Events and delegates work hand-in-hand to provide a communication between code from one class to other class. When something happens in one class or one part of the code and other part of the code needs a notification, events are used. 

 

A C# event is a class member that is activated whenever the event it was designed for occurs. It starts with a class that declares an event. Any class, including the same class that the event is declared in, may register one of its methods for the event. This occurs through a delegate, which specifies the signature of the method that is registered for the event. The event keyword is a delegate modifier. It must always be used in connection with a delegate.

 

The delegate may be one of the pre-defined .NET delegates or one you declare yourself. Whichever is appropriate, you assign the delegate to the event, which effectively registers the method that will be called when the event fires.

 

10. How to Use Events and Delegates in C#?

 

Once an event is declared, it must be associated with one or more event handlers before it can be raised. An event handler is nothing but a method that is called using a delegate. Use the += operator to associate an event with an instance of a delegate that already exists.

 

Example:

  1. obj.MyEvent += new MyDelegate(obj.Display);  

An event has the value null if it has no registered listeners.

 

Although events are mostly used in Windows controls programming, they can also be implemented in console, web and other applications.

 

Program for creating a custom Singlecast delegate and event

  1. using System;  
  2. namespace delegate_custom  
  3. {  
  4. class Program  
  5. {  
  6. public delegate void MyDelegate(int a);  
  7.   
  8. public class XX  
  9. {  
  10. public event MyDelegate MyEvent;  
  11.   
  12. public void RaiseEvent()  
  13. {  
  14. MyEvent(20);  
  15. Console.WriteLine("Event Raised");  
  16. }  
  17.   
  18. public void Display(int x)  
  19. {  
  20. Console.WriteLine("Display Method {0}", x);  
  21. }  
  22. }  
  23.   
  24. static void Main(string[] args)  
  25. {  
  26.   
  27. XX obj = new XX();  
  28. obj.MyEvent += new MyDelegate(obj.Display);  
  29.   
  30. obj.RaiseEvent();  
  31. Console.ReadLine();  
  32. }  
  33. }  
  34. }  

Program for creating custom a multiplecast delegate and event

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace delegate_custom_multicast  
  7. {  
  8. class Program  
  9. {  
  10. public delegate void MyDelegate(int a, int b);  
  11.   
  12. public class XX  
  13. {  
  14. public event MyDelegate MyEvent;  
  15.   
  16. public void RaiseEvent(int a, int b)  
  17. {  
  18. MyEvent(a, b);  
  19. Console.WriteLine("Event Raised");  
  20. }  
  21.   
  22. public void Add(int x, int y)  
  23. {  
  24. Console.WriteLine("Add Method {0}", x + y);  
  25. }  
  26.   
  27. public void Subtract(int x, int y)  
  28. {  
  29. Console.WriteLine("Subtract Method {0}", x - y);  
  30. }  
  31. }  
  32.   
  33. static void Main(string[] args)  
  34. {  
  35.   
  36. XX obj = new XX();  
  37. obj.MyEvent += new MyDelegate(obj.Add);  
  38. obj.MyEvent += new MyDelegate(obj.Subtract);  
  39. obj.RaiseEvent(20, 10);  
  40. Console.ReadLine();  
  41. }  
  42. }  
  43. }  

No comments:

Post a Comment

.Net References