Sunteți pe pagina 1din 58

overloading comes with in class for example :

Operator Overloading and Method overloading.

void Add( int i );


void Add( char c );

These two function declaration and definition in the same class is called method OVERLOADING.

overriding comes with two class ( base and drived class )

function in the base class is like

public virtual void Display();

function in the drived class is like

public override void Display();

this function overrides the base class .

I think you should know more on OOPs , Polimorphism , inheritance etc.

Overriding - same method names with same arguments and same return types associated in a class and its
subclass.

Overloading - same method name with different arguments, may or may not be same return type written in the
same class itself.

Example for overriding


Clas A
{
Virtual void hi(int a)
{
}
}

Class B:A
{
public overrid void hi(int a)
{

}
}

Example for Over loading

Class A
{
class a()
{

}
class a(int a)
{
}
}

When overriding, you change the method behavior for a derived class. Overloading simply involves having a
method with the same name within the class.

Example for overriding


Clas A
{
Virtual void hi(int a)
{
}
}

Class B:A
{
public overrid void hi(int a)
{

}
}

Example for Over loading

Class A
{
class a()

}
class a(int a)
{
}
}

……………………………….
In Overloading, the method name remains the same, but the signatures must be different. In Overriding, the
method name and the signature must be the same.
……………………………………
Over Loading and Overriding :--

In a class if two method is having the same name and different signature,its known as overloading in Object
oriented concepts.

For eg Take the case of a Shape Class. having a method with a name DrawShape();

This method has two definitins with different parameters.


1. public void DrawShape(int x1, int y1,int x2,int y2)
{
// draw a rectangle.
}

2. public void DrawShape(int x1,int y1)


{

// draw aline.
}

These two method does different operation based on the parameters. so through the same
interface (method name) the user is will be able to do multiple tasks (draw line and rectangle).This is called over
loading, and is an example of polymorphism.

Overriding :--

Overriding means, to give a specific definition by the derived class for a method implemented in the base class.

For eg.

Class Rectangle
{

publc void DrawRectangle()


{
// this method will draw a rectangle.
}

Class RoundRectangle : Rectanlge


{

public void DrawRectangle()


{

//Here the DrawRectangle() method is overridden in the


// derived class to draw a specific implementation to the
//derived class, i.e to draw a rectangle with rounded corner.

}
}

In the above example, the RoundedRectangle class needs to have its own
implementation of the DrawRectangle() method,i.e to draw a rectangle with
rounded corners. so it overloaded and gave it implementation.
……………………..

When overriding, you change the method behavior for a derived class. Overloading simply involves having a
method with the same name within the class.

overriding keyword cahnge behavour in derive class with same signature,

Overloading means same name but passing different datatype or different number arguments within the same
class

……………………………..

“overloading” is having the functions (methods) with the same name but different signatures. You can find
overloading in non object oriented languages like C too. Overloading acts on different data types in different
ways.

“overriding” is having a methods with same name and same signature in a parent class and the child class.
You cant find overloading in non-object oriented languages like C, because they dont have a class concept.
Overriding acts on different object types in different ways.

…………………………………

1. Whats the difference between overloading and overriding?

overloading is the definition of several functions with the same name


but different arguments and/or a different number of arguments.

void Foo(int);
void Foo(int, int);
void Foo(char);

overriding is writing a different body (in a derived class) for a


function defined in a base class.

class base
{
public:
int Foo()
{
return 1;
}
};

class derived: public base


{
public:
int Foo()
{
return 2;
}
};
[color=blue]
overloading is the definition of several functions with the same name
> but different arguments and/or a different number of arguments.
>
> void Foo(int);
> void Foo(int, int);
> void Foo(char);
>[/color]

Just to add,
Overloading can be done without usage of classes. However if you are
using a class then these functions have to be in the same class.

Also, the return type is not relevant. Soo, as said above only the
function name should be same while paramter type/number must be
differnt.

Delegates

The runtime supports reference types called delegates that serve a purpose similar to that of function pointers
in C++. Unlike function pointers, delegates are secure, verifiable, and type safe. A delegate type can represent
any method with a compatible signature. While function pointers can only represent static functions, a delegate
can represent both static and instance methods. Delegates are used for event handlers and callback functions in
the .NET Framework.
All delegates inherit from MulticastDelegate, which inherits from Delegate. The C#, Visual Basic, and C++
languages do not allow inheritance from these types, instead providing keywords for declaring delegates.
Because delegates inherit from MulticastDelegate, a delegate has an invocation list, which is a list of methods
that the delegate represents and that are executed when the delegate is invoked. All methods in the list receive
the arguments supplied when the delegate is invoked.
Note
The return value is not defined for a delegate that has more than one method in its invocation list, even if the
delegate has a return type.

Creating and Using Delegates


In many cases, such as callback methods, a delegate represents only one method, and the only actions you
need to take are creating the delegate and invoking it.
For delegates that represent multiple methods, the .NET Framework provides methods of the Delegate and
MulticastDelegate delegate classes to support operations such as adding a method to a delegate's invocation
list (the System.Delegate.Combine(System.Delegate[]) method), removing a method (the
System.Delegate.Remove(System.Delegate,System.Delegate) method), and getting the invocation list (the
System.Delegate.GetInvocationList method).
Note
It is not necessary to use these methods for event-handler delegates in C#, C++, and Visual Basic, as these
languages provide syntax for adding and removing event handlers.

Closed Static Delegates and Open Instance Delegates


Delegates can represent static (Shared in Visual Basic) or instance methods. Usually when a delegate
represents an instance method, the instance is bound to the delegate along with the method. For example, an
event-handler delegate might have three instance methods in its invocation list, each with a reference to the
object the method belongs to.
In the .NET Framework version 2.0, it is also possible to create an open delegate for an instance method. An
instance method has an implicit instance parameter (represented by this in C# or Me in Visual Basic), and it
can be represented by a delegate type that exposes this hidden parameter. That is, the delegate type must
have an extra parameter at the beginning of its formal parameter list, of the same type as the class the method
belongs to. The converse of this scenario is also supported, so that it is possible to bind the first argument of a
static method.
Note
The creation of open instance and closed static delegates is not directly supported by Visual Basic, C++, or C#
for delegate constructors. Instead, use one of the System.Delegate.CreateDelegate method overloads that
specifies MethodInfo objects, such as
System.Delegate.CreateDelegate(System.Type,System.Object,System.Reflection.MethodInfo,System.Boolean).

Relaxed Rules for Delegate Binding


In the .NET Framework version 2.0, the parameter types and return type of a delegate must be compatible with
the parameter types and return type of the method the delegate represents; the types do not have to match
exactly.
Note
In the .NET Framework versions 1.0 and 1.1, the types must match exactly.

A parameter of a delegate is compatible with the corresponding parameter of a method if the type of the
delegate parameter is more restrictive than the type of the method parameter, because this guarantees that an
argument passed to the delegate can be passed safely to the method.
Similarly, the return type of a delegate is compatible with the return type of a method if the return type of the
method is more restrictive than the return type of the delegate, because this guarantees that the return value of
the method can be cast safely to the return type of the delegate.
For example, a delegate with a parameter of type Hashtable and a return type of Object can represent a method
with a parameter of type Object and a return value of type Hashtable.
For more information and example code, see
System.Delegate.CreateDelegate(System.Type,System.Object,System.Reflection.MethodInfo).

Delegates and Asynchronous Method Calls


Every delegate has a BeginInvoke method that allows you to call the delegate asynchronously, and an
EndInvoke method that cleans up resources afterward. These methods are generated automatically for each
delegate type. When a delegate is invoked by using the BeginInvoke method, the method the delegate
represents is executed on a thread belonging to the ThreadPool.
For more information and

……………………….
Delegates in C#

A delegate in C# allows you to pass methods of one class to objects of other classes that can call those
methods. You can pass method m in Class A, wrapped in a delegate, to class B and Class B will be able to call
method m in class A. You can pass both static and instance methods. This concept is familiar to C++ developers
who have used function pointers to pass functions as parameters to other methods in the same class or in
another class. The concept of delegate was introduced in Visulal J++ and then carried over to C#. C# delegates
are implemented in .Net framework as a class derived from System.Delegate. Use of delegate involves four
steps.

1. Declare a delegate object with a signature that exactly matches the method signature that you are trying to
encapsulate.
2. Define all the methods whose signatures match the signature of the delegate object that you have defined in
step 1.
3. Create delegate object and plug in the methods that you want to encapsulate.
4. Call the encapsulated methods through the delegate object.

The following C# code shows the above four steps implemented using one delegate and four classes. Your
implementation will vary depending on the design of your classes.

using System;
//Step 1. Declare a delegate with the signature of the encapsulated method
public delegate void MyDelegate(string input);
//Step 2. Define methods that match with the signature of delegate declaration
class MyClass1{
public void delegateMethod1(string input){
Console.WriteLine("This is delegateMethod1 and the input to the method is {0}",input);
}
public void delegateMethod2(string input){
Console.WriteLine("This is delegateMethod2 and the input to the method is {0}",input);
}
}
//Step 3. Create delegate object and plug in the methods
class MyClass2{
public MyDelegate createDelegate(){
MyClass1 c2=new MyClass1();
MyDelegate d1 = new MyDelegate(c2.delegateMethod1);
MyDelegate d2 = new MyDelegate(c2.delegateMethod2);
MyDelegate d3 = d1 + d2;
return d3;
}
}
//Step 4. Call the encapsulated methods through the delegate
class MyClass3{
public void callDelegate(MyDelegate d,string input){
d(input);
}
}
class Driver{
static void Main(string[] args){
MyClass2 c2 = new MyClass2();
MyDelegate d = c2.createDelegate();
MyClass3 c3 = new MyClass3();
c3.callDelegate(d,"Calling the delegate");
}
}

Imagine that you need your program to call a method, but you can't know what that method will be until run-
time. Perhaps it's a sort method, such as a bubble sort, merge sort, or quick sort. What if your algorithm needs a
mathematical function, but the exact algorithm can't be determined until specific data is analyzed? Sometimes,
generic GUI events and controls need to provide notification mechanisms for their events, but only the
developer knows which callbacks are appropriate for a given implementation. All of these situations are practical
applications and reasons for using delegates.

With delegates, you can reference methods and build algorithms that work, regardless of what those methods
are. If you're familiar with C++, you might recognize this as being the same as function pointers. However, the
difference with C# is that delegates are object-oriented and type safe.

Click here to read a quick introduction to C# delegates.

Delegate Signatures

A delegate type is specified by a distinct signature, which includes a unique identifier, parameter list, and return
type. The following code shows how to declare a delegate:

public delegate double UnitConversion(double from);

The example above contains a full definition of a delegate. Just like any other namespace element, delegates
are declared as either public or internal, with a default of internal accessibility if the modifier is not specified.
Delegates may also be declared as nested types, with accessibility modifiers allowable for their containing class
or struct.

The C# keyword delegate identifies this as a delegate declaration. The return type of this delegate is double,
its identifier is "UnitConversion," and it has a single parameter of type double. Looking at both the delegate
identifier and parameter identifier, you can get an idea of the purpose of this delegate, which is to serve as a
definition of methods that perform a conversion of units from one type to another.

A delegate declaration is appended with a semi-colon. Delegates do not have implementation. Instead, they are
a skeleton defining the proper signature of delegate handler methods to which they may refer. The handler
methods contain implementation that is executed when its referring delegate is invoked.

………………….

Summary

In this article I discuss the event handling model in .NET using C#. The discussion starts with an introduction to
the concept of delegates and then it extends that concept to events and event handling in .NET. Finally, I apply
these concepts to GUI event handling using windows forms. Complete code is provided in each step of the
discussions.

Introduction
Event handling is familiar to any developer who has programmed graphical user interfaces (GUI). When a user
interacts with a GUI control (e.g., clicking a button on a form), one or more methods are executed in response to
the above event. Events can also be generated without user interactions. Event handlers are methods in an
object that are executed in response to some events occurring in the application. To understand the event
handling model of .Net framework, we need to understand the concept of delegate.

Delegates in C#

A delegate in C# allows you to pass methods of one class to objects of other classes that can call those
methods. You can pass method m in Class A, wrapped in a delegate, to class B and Class B will be able to call
method m in class A. You can pass both static and instance methods. This concept is familiar to C++ developers
who have used function pointers to pass functions as parameters to other methods in the same class or in
another class. The concept of delegate was introduced in Visulal J++ and then carried over to C#. C# delegates
are implemented in .Net framework as a class derived from System.Delegate. Use of delegate involves four
steps.

1. Declare a delegate object with a signature that exactly matches the method signature that you are trying to
encapsulate.
2. Define all the methods whose signatures match the signature of the delegate object that you have defined in
step 1.
3. Create delegate object and plug in the methods that you want to encapsulate.
4. Call the encapsulated methods through the delegate object.

The following C# code shows the above four steps implemented using one delegate and four classes. Your
implementation will vary depending on the design of your classes.

using System;
//Step 1. Declare a delegate with the signature of the encapsulated method
public delegate void MyDelegate(string input);
//Step 2. Define methods that match with the signature of delegate declaration
class MyClass1
{
public void delegateMethod1(string input)
{
Console.WriteLine("This is delegateMethod1 and the input to the method is {0}",input);
}
public void delegateMethod2(string input)
{
Console.WriteLine("This is delegateMethod2 and the input to the method is {0}",input);
}
}
//Step 3. Create delegate object and plug in the methods
class MyClass2
{
public MyDelegate createDelegate()
{
MyClass1 c2=new MyClass1();
MyDelegate d1 = new MyDelegate(c2.delegateMethod1);
MyDelegate d2 = new MyDelegate(c2.delegateMethod2);
MyDelegate d3 = d1 + d2;
return d3;
}
}
//Step 4. Call the encapsulated methods through the delegate
class MyClass3
{
public void callDelegate(MyDelegate d,string input)
{
d(input);
}
}
class Driver
{
static void Main(string[] args)
{
MyClass2 c2 = new MyClass2();
MyDelegate d = c2.createDelegate();
MyClass3 c3 = new MyClass3();
c3.callDelegate(d,"Calling the delegate");
}
}

Event handlers in C#

An event handler in C# is a delegate with a special signature, given below.

public delegate void MyEventHandler(object sender, MyEventArgs e);

The first parameter (sender) in the above declaration specifies the object that fired the event. The second
parameter (e) of the above declaration holds data that can be used in the event handler. The class MyEventArgs
is derived from the class EventArgs. EventArgs is the base class of more specialized classes, like
MouseEventArgs, ListChangedEventArgs, etc. For GUI event, you can use objects of these specialized EventArgs
classes without creating your own specialized EventArgs classes. However, for non GUI event, you need to
create your own specialized EventArgs class to hold your data that you want to pass to the delegate object. You
create your specialized EventArgs class by deriving from EventArgs class.

public class MyEventArgs : EventArgs


{
public string m_myEventArgumentdata;
}

In case of event handler, the delegate object is referenced using the key word event as follows:

public event MyEventHandler MyEvent;

Now, we will set up two classes to see how this event handling mechanism works in .Net framework. The step 2
in the discussion of delegates requires that we define methods with the exact same signature as that of the
delegate declaration. In our example, class A will provide event handlers (methods with the same signature as
that of the delegate declaration). It will create the delegate objects (step 3 in the discussion of delegates) and
hook up the event handler. Class A will then pass the delegate objects to class B. When an event occurs in Class
B, it will execute the event handler method in Class A.

using System;
//Step 1 Create delegate object
public delegate void MyHandler1(object sender,MyEventArgs e);
public delegate void MyHandler2(object sender,MyEventArgs e);
//Step 2 Create event handler methods
class A
{
public const string m_id="Class A";
public void OnHandler1(object sender,MyEventArgs e)
{
Console.WriteLine("I am in OnHandler1 and MyEventArgs is {0}", e.m_id);
}
public void OnHandler2(object sender,MyEventArgs e)
{
Console.WriteLine("I am in OnHandler2 and MyEventArgs is {0}", e.m_id);
}
//Step 3 create delegates, plug in the handler and register with the object that will fire the events
public A(B b)
{
MyHandler1 d1=new MyHandler1(OnHandler1);
MyHandler2 d2=new MyHandler2(OnHandler2);
b.Event1 +=d1;
b.Event2 +=d2;
}
}
//Step 4 Calls the encapsulated methods through the delegates (fires events)
class B
{
public event MyHandler1 Event1;
public event MyHandler2 Event2;
public void FireEvent1(MyEventArgs e)
{
if(Event1 != null)
{
Event1(this,e);
}
}
public void FireEvent2(MyEventArgs e)
{
if(Event2 != null)
{
Event2(this,e);
}
}
}
public class MyEventArgs : EventArgs
{
public string m_id;
}
public class Driver
{
public static void Main()
{
B b= new B();
A a= new A(b);
MyEventArgs e1=new MyEventArgs();
MyEventArgs e2=new MyEventArgs();
e1.m_id ="Event args for event 1";
e2.m_id ="Event args for event 2";
b.FireEvent1(e1);
b.FireEvent2(e2);
}
}

GUI Event Handling in C#

Event handling in Windows Forms (.NET frame work that supports GUI application) employ the .NET event
handling model described earlier. We will now apply that model to write a simple application. The application
has one class, MyForm, derived from System.Windows.Forms.Form class. Class MyForm is derived from Form
class. If you study the code and the three comment lines, you will observe that you do not have to declare the
delegates and reference those delegates using event keyword because the events (mouse click, etc.) for the GUI
controls (Form, Button, etc.) are already available to you and the delegate is System.EventHandler. However,
you still need to define the method, create the delegate object (System.EventHandler) and plug in the method,
that you want to fire in response to the event (e.g. a mouse click), into the delegate object.

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
public class MyForm : Form
{
private Button m_nameButton;
private Button m_clearButton;
private Label m_nameLabel;
private Container m_components = null;
public MyForm()
{
initializeComponents();
}
private void initializeComponents()
{
m_nameLabel=new Label();
m_nameButton = new Button();
m_clearButton = new Button();
SuspendLayout();
m_nameLabel.Location=new Point(16,16);
m_nameLabel.Text="Click NAME button, please";
m_nameLabel.Size=new Size(300,23);
m_nameButton.Location=new Point(16,120);
m_nameButton.Size=new Size(176, 23);
m_nameButton.Text="NAME";
//Create the delegate, plug in the method, and attach the delegate to the Click event of the button
m_nameButton.Click += new System.EventHandler(NameButtonClicked);
m_clearButton.Location=new Point(16,152);
m_clearButton.Size=new Size(176,23);
m_clearButton.Text="CLEAR";
//Create the delegate, plug in the method, and attach the delegate to the Click event of the button
m_clearButton.Click += new System.EventHandler(ClearButtonClicked);
this.ClientSize = new Size(292, 271);
this.Controls.AddRange(new Control[]
m_nameLabel,m_nameButton,m_clearButton});
this.ResumeLayout(false);
}
//Define the methods whose signature exactly matches with the declaration of the delegate
private void NameButtonClicked(object sender, EventArgs e)
{
m_nameLabel.Text="My name is john, please click CLEAR button to clear it";
}
private void ClearButtonClicked(object sender,EventArgs e)
{
m_nameLabel.Text="Click NAME button, please";
}
public static void Main()
{
Application.Run(new MyForm());
}
}

Conclusion

Other popular object oriented languages like, Java and Smalltalk do not have the concept of delegates. It is new
to C# and it derives its root from C++ and J++. I hope that the above discussions will clear this concept to
programmers who are starting out C# as their first object oriented language. If you are using Visual Studio IDE
for your C# GUI development, attaching your delegate methods to the events generated by GUI controls (like
mouse click on a button) can be done without you writing the code. Still, it is better to know what is going on
under the hood.

One of the key aspects of C# programming in particular, and .NET programming in general, is using delegates
to handle events. In Programming C#, 3rd Edition, I approach teaching delegates and events somewhat
differently than I had in previous editions.

This article will focus on one aspect of delegates: how they are used to implement event handling. It is
important to understand that while delegates are a general-purpose mechanism for calling methods indirectly,
their principal uses in .NET are for a) implementing events and b) implementing call-back methods.

To get a sense of how delegates are used to implement events, we'll look at the implementation of a custom
event.

Implementing a Custom Event

In C#, any object can publish a set of events to which other classes can subscribe. When the publishing class
raises an event, all the subscribed classes are notified. This design is a form of the Observer Pattern described in
the seminal work Design Patterns, by Gamma, et al. (Addison Wesley, 1995). Gamma describes the intent of this
pattern: "Define a one-to-many dependency between objects so that when one object changes state, all its
dependents are notified and updated automatically."

With this mechanism, your object can say "Here are things I can notify you about," and other classes might sign
up, saying "Yes, let me know when that happens." For example, a button might notify any number of interested
observers when it is clicked. The button is called the "publisher," because the button publishes the Click event,
and the other classes are the subscribers, because they subscribe to the Click event.

As a second example, a Clock might notify interested classes whenever the time changes by one second. The
Clock class could simply print the time rather than raising an event, so why bother with the indirection of using
delegates? The advantage of the publish/subscribe idiom is that any number of classes can be notified when an
event is raised. The subscribing classes do not need to know how the Clock works, and the Clock does not need
to know what they are going to do in response to the event.

The publisher and the subscribers are decoupled by the delegate. This is highly desirable; it makes for more
flexible and robust code. The Clock can change how it detects time without breaking any of the subscribing
classes. The subscribing classes can change how they respond to time changes without breaking the Clock. The
two classes spin independently of one another, and that makes for code that is easier to maintain.

A method that handles an event is called an event handler. You can declare your event handlers as you would
any other delegate. By convention, event handlers in the .NET Framework return void and take two parameters:
The first parameter is the "source" of the event; that is, the publishing object. The second parameter is an
object derived from EventArgs. It is recommended that your event handlers follow this design pattern.

EventArgs is the base class for all event data. Other than its constructor, the EventArgs class inherits all of its
methods from Object, though it does add a public static field, named empty, which represents an event with no
state (to allow for the efficient use of events with no state). The EventArgs-derived class contains information
about the event.

Suppose you want to create a Clock class that uses delegates to notify potential subscribers whenever the local
time changes value by one second. Call this delegate SecondChangeHandler.

The declaration for the SecondChangeHandler delegate is:

public delegate void SecondChangeHandler(


object clock,
TimeInfoEventArgs timeInformation
);

This delegate will encapsulate any method that returns void and that takes two parameters. The first parameter
is an object that represents the clock (the object raising the event) and the second parameter is an object of
type TimeInfoEventArgs that will contain useful information for anyone interested in this event.

TimeInfoEventArgs is defined as follows:

public class TimeInfoEventArgs : EventArgs


{
public TimeInfoEventArgs(int hour, int minute, int second)
{
this.hour = hour;
this.minute = minute;
this.second = second;
}
public readonly int hour;
public readonly int minute;
public readonly int second;
}

The TimeInfoEventArgs object will have information about the current hour, minute, and second. It defines a
constructor and three public, readonly integer variables.

In addition to its delegate, a Clock has three member variables, hour, minute, and second, as well as a single
method, Run():
public void Run()
{
for(;;)
{
// sleep 10 milliseconds
Thread.Sleep(10);

// get the current time


System.DateTime dt = System.DateTime.Now;

// if the second has changed


// notify the subscribers
if (dt.Second != second)
{
// create the TimeInfoEventArgs object
// to pass to the subscriber
TimeInfoEventArgs timeInformation =
new TimeInfoEventArgs(
dt.Hour,dt.Minute,dt.Second);

// if anyone has subscribed, notify them


if (OnSecondChange != null)
{
OnSecondChange(this,timeInformation);
}
}
// update the state
this.second = dt.Second;
this.minute = dt.Minute;
this.hour = dt.Hour;
}
}

Run creates an infinite for loop that periodically checks the system time. If the time has changed from the Clock
object's current time, it notifies all of its subscribers and then updates its own state.

The first step is to sleep for 10 milliseconds:

Thread.Sleep(10);

After sleeping for 10 milliseconds, the method checks the current time:

System.DateTime dt = System.DateTime.Now;

About every 100 times it checks, the second will have incremented. The method notices that change and
notifies its subscribers. To do so, it first creates a new TimeInfoEventArgs object:

if (dt.Second != second)
{
TimeInfoEventArgs timeInformation =
new TimeInfoEventArgs(dt.Hour,dt.Minute,dt.Second);

It then notifies the subscribers by firing the OnSecondChange event (the if statement checks that the value is
not null, ensuring that there are subscribers before calling OnSecondChange).
if (OnSecondChange != null)
{
OnSecondChange(this,timeInformation);
}

You will remember that OnSecondChange takes two arguments: the source of the event and the object derived
from EventArgs. In the code snippet, you see that the clock's this reference is passed because the clock is the
source of the event. The second parameter is the TimeInfoEventArgs object timeInformation, created on the line
above.

…………….

delegate

A delegate declaration defines a reference type that can be used to encapsulate a method with a specific
signature. A delegate instance encapsulates a static or an instance method. Delegates are roughly similar to
function pointers in C++; however, delegates are type-safe and secure.

This declaration takes the following form::

[attributes] [modifiers] delegate result-type identifier ([formal-parameters]);

where:

attributes (Optional)
Additional declarative information. For more information on attributes and attribute classes, see 17.
Attributes.
modifiers (Optional)
The allowed modifiers are new and the four access modifiers.
result-type
The result type, which matches the return type of the method.
identifier
The delegate name.
formal-parameters (Optional)
Parameter list. If a parameter is a pointer, the delegate must be declared with the unsafe modifier.

Remarks

A delegate lets you pass a function as a parameter. The type safety of delegates requires the function you pass
as a delegate to have the same signature as the delegate declaration. See the Delegates Tutorial for more
information on using delegates.

The Delegates Tutorial shows how to compose delegates, that is, create delegates from other delegates. A
delegate that contains an out parameter cannot be composed.
Delegates are the basis for events.

For more information on delegates, see 15. Delegates.

Example 1

The following is a simple example of declaring and using a delegate.

Copy Code

// keyword_delegate.cs

// delegate declaration

delegate void MyDelegate(int i);

class Program

public static void Main()

TakesADelegate(new MyDelegate(DelegateFunction));

public static void TakesADelegate(MyDelegate SomeFunction)

SomeFunction(21);

public static void DelegateFunction(int i)

System.Console.WriteLine("Called by delegate with number: {0}.", i);

}
Output
Copy Code

Called by delegate with number: 21.

Example 2

In the following example, one delegate is mapped to both static and instance methods and returns specific
information from each.

Copy Code

// keyword_delegate2.cs

// Calling both static and instance methods from delegates

using System;

// delegate declaration

delegate void MyDelegate();

public class MyClass

public void InstanceMethod()

Console.WriteLine("A message from the instance method.");

static public void StaticMethod()

Console.WriteLine("A message from the static method.");

}
public class MainClass

static public void Main()

MyClass p = new MyClass();

// Map the delegate to the instance method:

MyDelegate d = new MyDelegate(p.InstanceMethod);

d();

// Map to the static method:

d = new MyDelegate(MyClass.StaticMethod);

d();

Output
Copy Code

A message from the instance method.

A message from the static method.

……………………

Using Delegates (C# Programming Guide)

A delegate is a type that safely encapsulates a method, similar to a function pointer in C and C++. Unlike C
function pointers, delegates are object-oriented, type safe, and secure. The type of a delegate is defined by the
name of the delegate. The following example declares a delegate named Del that can encapsulate a method
that takes a string as an argument and returns void:

C#
Copy Code

public delegate void Del(string message);


A delegate object is normally constructed by providing the name of the method the delegate will wrap, or with
an anonymous Method. Once a delegate is instantiated, a method call made to the delegate will be passed by
the delegate to that method. The parameters passed to the delegate by the caller are passed to the method,
and the return value, if any, from the method is returned to the caller by the delegate. This is known as invoking
the delegate. An instantiated delegate can be invoked as if it were the wrapped method itself. For example:

C#
Copy Code

// Create a method for a delegate.

public static void DelegateMethod(string message)

System.Console.WriteLine(message);

C#
Copy Code

// Instantiate the delegate.

Del handler = DelegateMethod;

// Call the delegate.

handler("Hello World");

Delegate types are derived from the Delegate class in the .NET Framework. Delegate types are sealed—they
cannot be derived from— and it is not possible to derive custom classes from Delegate. Because the
instantiated delegate is an object, it can be passed as a parameter, or assigned to a property. This allows a
method to accept a delegate as a parameter, and call the delegate at some later time. This is known as an
asynchronous callback, and is a common method of notifying a caller when a long process has completed. When
a delegate is used in this fashion, the code using the delegate does not need any knowledge of the
implementation of the method being used. The functionality is similar to the encapsulation interfaces provide.
For more information, see When to Use Delegates Instead of Interfaces.

Another common use of callbacks is defining a custom comparison method and passing that delegate to a sort
method. It allows the caller's code to become part of the sort algorithm. The following example method uses the
Del type as a parameter:

C#
Copy Code

public void MethodWithCallback(int param1, int param2, Del callback)

callback("The number is: " + (param1 + param2).ToString());

You can then pass the delegate created above to that method:

C#
Copy Code

MethodWithCallback(1, 2, handler);

and receive the following output to the console:

The number is: 3

Using the delegate as an abstraction, MethodWithCallback does not need to call the console directly—it does not
have to be designed with a console in mind. What MethodWithCallback does is simply prepare a string and pass
the string to another method. This is especially powerful since a delegated method can use any number of
parameters.

When a delegate is constructed to wrap an instance method, the delegate references both the instance and the
method. A delegate has no knowledge of the instance type aside from the method it wraps, so a delegate can
refer to any type of object as long as there is a method on that object that matches the delegate signature.
When a delegate is constructed to wrap a static method, it only references the method. Consider the following
declarations:

C#
Copy Code

public class MethodClass

public void Method1(string message) { }

public void Method2(string message) { }

Along with the static DelegateMethod shown previously, we now have three methods that can be wrapped by a
Del instance.
A delegate can call more than one method when invoked. This is referred to as multicasting. To add an extra
method to the delegate's list of methods—the invocation list—simply requires adding two delegates using the
addition or addition assignment operators ('+' or '+='). For example:

C#
Copy Code

MethodClass obj = new MethodClass();

Del d1 = obj.Method1;

Del d2 = obj.Method2;

Del d3 = DelegateMethod;

//Both types of assignment are valid.

Del allMethodsDelegate = d1 + d2;

allMethodsDelegate += d3;

At this point allMethodsDelegate contains three methods in its invocation list—Method1, Method2, and
DelegateMethod. The original three delegates, d1, d2, and d3, remain unchanged. When allMethodsDelegate is
invoked, all three methods are called in order. If the delegate uses reference parameters, the reference is
passed sequentially to each of the three methods in turn, and any changes by one method are visible to the
next method. When any of the methods throws an exception that is not caught within the method, that
exception is passed to the caller of the delegate and no subsequent methods in the invocation list are called. If
the delegate has a return value and/or out parameters, it returns the return value and parameters of the last
method invoked. To remove a method from the invocation list, use the decrement or decrement assignment
operator ('-' or '-='). For example:

C#
Copy Code

//remove Method1

allMethodsDelegate -= d1;

// copy AllMethodsDelegate while removing d2

Del oneMethodDelegate = allMethodsDelegate - d2;


Because delegate types are derived from System.Delegate, the methods and properties defined by that class
can be called on the delegate. For example, to find the number of methods in a delegate's invocation list, you
may write:

C#
Copy Code

int invocationCount = d1.GetInvocationList().GetLength(0);

Delegates with more than one method in their invocation list derive from MulticastDelegate, which is a subclass
of System.Delegate. The above code works in either case because both classes support GetInvocationList.

Multicast delegates are used extensively in event handling. Event source objects send event notifications to
recipient objects that have registered to receive that event. To register for an event, the recipient creates a
method designed to handle the event, then creates a delegate for that method and passes the delegate to the
event source. The source calls the delegate when the event occurs. The delegate then calls the event handling
method on the recipient, delivering the event data. The delegate type for a given event is defined by the event
source. For more, see Events (C# Programming Guide).

Comparing delegates of two different types assigned at compile-time will result in a compilation error. If the
delegate instances are statically of the type System.Delegate, then the comparison is allowed, but will return
false at run time. For example:

C#
Copy Code

delegate void Delegate1();

delegate void Delegate2();

static void method(Delegate1 d, Delegate2 e, System.Delegate f)

// Compile-time error.

//Console.WriteLine(d == e);

// OK at compile-time. False if the run-time type of f

//is not the same as that of d.

System.Console.WriteLine(d == f);
}

……………..

Delegates and Event Handling in C#


By Faisal Jawaid

Introduction:

This article will deal with Event and delegates in C#. C# Open a new door by including the feature of Event
Driven programming such as Events and Delegates. This article is part of the series that helps in understanding
Events and Delegates.

Events are the means by which Windows Application receive notification. In a Windows application a lot of
Events are occurring at a particular instant for e.g. Mouse Move, Mouse out, Mouse Click etc. Delegates are
pointer to the function and are type-safe. This Article will cover the Single delegate, Multi-cast delegates and
Event Driven programming using C#. The first part of this article will focus delegates and its types and the
remaining part is on Events.

Delegates:

Another very interesting feature in C# is delegates. Delegates are best complemented as new type of Object in
C#. They are also represented as pointer to functions. Technically delegate is a reference type used to
encapsulate a method with a specific signature and return type. Since in this article delegate discussion is event
centric. If we consider a real world scenario then delegates can be understood as any delegate representing a
country a group of people representing a company etc. This same definition can be mapped to C# as delegate
act as an intermediary between event source and destination. The DotNetFrameWork has a Name Space
System.Delagate. We have two flavors of delegate in C#.

· Single Delegate
· Multi-cast Delegate
Single Delegates:

A delegate is called a single delegate that derives from the System.Delegate class contains an invocation list
with one method. Now we will look at how the single-cast delegates are declared. In single-cast delegates, the
delegate can point to both static and non-static method if both have the same signature as the delegate. Look
at the code below how to declare a single-cast delegate.

public delegate void Myfunction(string,System.Int32)

The above code shows a simple delegate which will point to a method with no return type and taking two
arguments as parameters. Now we see delegate that return a value.

public delegate bool MyFunctionOne();

Consider a simple example

using System;

namespace ConsoleApplication
{
/// <summary>
/// Summary description for Name.
/// </summary>

public class Name


{
public Name()
{
//
// TODO: Add constructor logic here
//
}

public string Compare(string NameOne, string NameTwo)


{
System.Int32 result=NameOne.CompareTo(NameTwo);

if(result==0)
{
return NameOne;
}
else
{
Console.WriteLine(NameTwo +""+ NameTwo);
return NameTwo+" "+NameOne;
}
}
}
}
Description of the Above Code:

The above example doesn't show the true usage of delegates but I think we are getting the idea what we want
to understand. Above is a simple program which compares two strings. If the strings are equal then only one
name is returned otherwise both the names are returned if the condition executes to false. Now first the main
method is invoked which is situated in DelegateExample Class. In this class we have also declared our delegate.

public delegate string CompareNames(string NameOne,string NameTwo);

It accepts two arguments of type string and also returns a string. In the main method we create the instance of
Name class and then we create the instance of our delegate passing the name of our method in it as its
argument so that it points to compare method now. Then we just call our delegates by passing the arguments.
Which in return call the Compare method and return the string.

Multi-cast Delegates:

A delegate is called Multi-cast Delegate that derives from the System.MulticastDelegate contains an invocation
list with multiple methods. At times it is desirable to call two methods through a single delegate. This can be
achieved through Single-cast Delegate but it is different from having a collection, each of which invokes a single
method.

In Multi-casting you create a single delegate that will invoke multiple encapsulated methods. The return type of
all the delegates should be same. Now the question why are we using Multi-cast delegates when Single-cast
delegates are enough. Well the answer to this question is what if you want to call three methods when a button
is clicked. The Multi-cast delegates are used with events where multiple call to different methods are required.
System.MulticastDelegate contains two methods Combine and Remove. The Combine is a static method of class
System.MulticastDelegate and is used to Combine the delegates and the remove method is used to remove the
delegate from the list. For user convenience we have += operator overloaded for delegate Combine method
and -= operator overloaded for Remove method Multi-cast delegates are similar to Single-cast delegates for e.g.

public delegate void MulticastDelegate();

Multi-cast delegate can have arguments and can return value as well. All the Methods pointed by delegates
should return the similar value as the delegate return type.

public delegate string MultiCastOne(string Name);

Consider a simple example:

using System;

namespace Multi_castDelegate
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class MyClassDelegate
{
/// <summary>
/// The main entry point for the application.
/// </summary>

public delegate string StringDelegate(string s);


}
}
Below is the class that defines the static methods having same signature as delegate.
using System;

namespace Multi_castDelegate
{
/// <summary>
/// Summary description for MyImplementingClass.
/// </summary>
public class MyClass
{
public MyClass()
{

public static string WriteString(string s)


{
Console.WriteLine("Writing string");
return "null";
}

public static string logString(string s)


{
Console.WriteLine("loging string");
return "null";
}

public static string TransmitString(string s)


{
Console.WriteLine("Transmitting string");
return "null";

}
}
}
The Main class:
using System;
using System.Threading;
namespace Multi_castDelegate
{
/// <summary>
/// Summary description for Test.
/// </summary>
public class Test
{
public static void Main()
{
MyClassDelegate.StringDelegate
Writer,Logger,Transmitter;

MyClassDelegate.StringDelegate
myDelegate;

Writer=new
MyClassDelegate.StringDelegate(MyClass.WriteString);
/// calling Writer
Writer("hello i am Writer just acting like Single cast");
Logger=new MyClassDelegate.StringDelegate(MyClass.logString);
///calling Logger
Logger("hello i am Logger just acting like Single-cast");
Transmitter=new MyClassDelegate.StringDelegate(MyClass.TransmitString);
///calling Transmitter
Transmitter("hello i am Transmitter just acting like Single-cast");
///here mydelegate used the Combine method of System.MulticastDelegate
///and the delegates combine
myDelegate=(MyClassDelegate.StringDelegate)System.Delegate.Combine(Writer,Logger);
myDelegate("used Combine");
///here Transmitter is also added using the overloaded form of Combine
myDelegate+=Transmitter;
myDelegate("Using Overloaded Form");
///now using the Remove method
myDelegate=(MyClassDelegate.StringDelegate)System.Delegate.Remove(myDelegate,Writer);
myDelegate("Without Writer");
///overloaded Remove
myDelegate-=Transmitter;
myDelegate("Without Transmitter");
System.Threading.Thread.Sleep(2300);

}
}
}
Description of the Above Code:

The above program contains three classes, MyClassDelegate contains the delegate.

public delegate string StringDelegate(string s);

The class MyClass Contains the static methods that contains the static methods that have a similar signature as
the delegate StringDelegate. The third class is the Test Class which shows how to combine the delegates and
how to remove the delegate from the list.

Events:

Events are the messages sent by an object to indicate the occurrence of an event. Event can also be defined as
a member that enables an object to provide notification. Events provide a very powerful means of inter-process
communication. The most familiar example of events are graphical user interface, events are fired when any
control is clicked on the GUI.

Events are not used only for graphical user interfaces. Events provide a generally useful way for objects to
signal state changes that may be useful to the client of that object. In C# events are used with delegates. If you
don't have through understanding of delegates please refer the above portion. In event communication the
event raiser class doesn't know who is going to handle the event now the delegates comes into play that acts as
an intermediary between the source and the receiver.

Delegate:

public delegate void newdelegate();

Event Declaration:

public event newdelegate newevent;

We can categories events into two types

· Customized Events
· Predefined Events
1. Customized Events:

Don't confuse these terms because I have categorized events so that the explanation become simple. Now what
do we mean by customize events, they are events which we define according to our needs and are not defined.
For e.g we want to raise an event whenever a dynamic control is created on the form. To declare an event, first
define the delegate for that event, if none is already declared. The delegate type defines the set of argument
that are to be passed to the method which will act as event handler.

Example of Customized Events:

namespace Eventhandling
{
public delegate void IamClicked();

/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public System.Int32 o_IntCounter=0;
public event IamClicked ClickMe;
System.Int32 o_intXaxis=120;
System.Int32 o_intYaxis=80;

public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after
InitializeComponent call
//
Button b1=new Button();
b1.Parent=this;
b1.Location=new Point(o_intXaxis,o_intYaxis);
b1.Name="Click1";
b1.Text="Click Me";
ClickMe+=new IamClicked(Show);
ClickMe();
}

/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows Form Designer generated code


/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(304, 237);
this.Name = "Form1";
this.Text = "Events";

}
#endregion

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
/// <summary>
/// Event Handler Function Which is called when the
/// Click Event is Raised.
/// </summary>
/// <param name="o"></param>
/// <param name="ea"></param>
public void Show()
{
MessageBox.Show("JUST BORN");
}
}
}
Description:

The above program shows hoe we can fire our own events. In this program a button is created dynamically.

Button b1=new Button();


b1.Parent=this;
b1.Location=new Point(o_intXaxis,o_intYaxis);
b1.Name="Click1";
b1.Text="Click Me";
ClickMe+=new IamClicked(Show);
ClickMe();
The delegate and event defined in above program are
public delegate void IamClicked();
public event IamClicked ClickMe;

The delegate points to the following function.


public void Show()
{
MessageBox.Show("JUST BORN");
}
When the ClickME event is fired the delegate attached to this event call the above function Show. Look at the
signature of the function and the delegate both are same. The function just shows a message box with the
message "Just Born".
2. Predefined Events:

Events and delegates go hand in hand. Now we are considering Predefined events like

· Click
· Closed
· Closing
· DragDrop
· Enter
· Load
· Leave
etc
We normally use predefined events in our programming practice. Multiple events can share the same delegate
type. The event is declared as the delegate type. In C# we must follow precise signature for Handler.
void OnClick(object o,EventArgs ea)
{
//Code
}
Example of Events:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace Eventhandling
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public System.Int32 o_IntCounter=0;
private System.Windows.Forms.Button btnNewControl;

public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();

//
// TODO: Add any constructor code after
InitializeComponent call
//
}

/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows Form Designer generated code


/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btnNewControl = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// btnNewControl
//
this.btnNewControl.Name = "btnNewControl";
this.btnNewControl.Size = new System.Drawing.Size(112, 32);
this.btnNewControl.TabIndex = 0;
this.btnNewControl.Text = "New Control";
this.btnNewControl.Click += new System.EventHandler(this.btnNewControl_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(304, 237);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.btnNewControl});
this.Name = "Form1";
this.Text = "Events";
this.ResumeLayout(false);

}
#endregion

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
/// <summary>
/// Event Handler Function Which is called when the
/// Click Event is Raised.
/// </summary>
/// <param name="o"></param>
/// <param name="ea"></param>
public void btnAdd(object o,EventArgs ea)
{

o_IntCounter++;
MessageBox.Show(o_IntCounter.ToString());

private void btnNewControl_Click(object sender, System.EventArgs e)


{
System.Int32 b_intCount;
System.Int32 b_intXaxis=120;
System.Int32 b_intYaxis=80;
for(b_intCount=1;b_intCount < = 3;b_intCount++,b_intYaxis+=20)
{
///new buttons are created at run time
///with there location and names.
Button b1=new Button();
b1.Parent=this;
b1.Location=new Point(b_intXaxis,b_intYaxis);
b1.Name="Click1"+b_intCount;
b1.Text="Click Me";
b1.Click+=new EventHandler(btnAdd);
}
}
}
}
Description:

The above program creates three buttons at run time and when any of the buttons is clicked the Click event of
that button is fired.

for(b_intCount=1;b_intCount < = 3;b_intCount++,b_intYaxis+=20)


{
///new buttons are created at run time
///with there location and names.
Button b1=new Button();
b1.Parent=this;
b1.Location=new Point(b_intXaxis,b_intYaxis);
b1.Name="Click1"+b_intCount;
b1.Text="Click Me";
b1.Click+=new EventHandler(btnAdd);
}
The Click event belongs to the button class. We will reference it when we are registering a delegate.

b1.Click+=new EventHandler(btnAdd);

The delegate EventHandler is also defined in the System namespace of Dot net Framework library. All what we
have to do is to define our callback function that is invoked when the button is clicked and accepts two
arguments object and EventArgs type conforms the signature of delegate EventHandler defined in System
namespace
public void btnAdd(object o,EventArgs ea)
{

o_IntCounter++;
MessageBox.Show(o_IntCounter.ToString());

The handler btnAdd() Method catches this event and shows a message box that indicates a number that how
many times these buttons are clicked. The above example is quite self explanatory so just copy the code in a
new project and run for yourself.

Introduction

One of my favorite features about good old C was function pointers. Those of you who haven't used function
pointers missed out on the fun. When C++ was out we also had pointers to member functions. The basic
problem with function pointers and pointers to member functions is that, neither of them is type-safe. The .NET
framework has a class named Delegate in the System namespace. Delegates are the .NET surrogate for function
pointers and pointers to member functions. The advantage with delegates is that delegates are fully managed
objects that are also type safe. A delegate basically encapsulates a method with a particular set of arguments
and return type. You can encapsulate only a method that matches the delegate definition in a delegate.
Delegates can encapsulate both static methods of a class as well as instance methods.

Delegates are called single-cast delegates when they encapsulate a single method, and are called multi-cast
delegates when they encapsulate more than one method. Multi-cast delegates are useful as event-handlers.
Multi-cast delegates should not be confused with an array of delegates. Multi-cast delegates are derived from
the MulticastDelegate class which is a child class of the Delegate class. When a multi-cast delegate is invoked,
the encapsulated methods are called synchronously in the same order in which they were added to the multi-
cast delegate. Managed C++ and C# offer language specific features that allow us to work with delegates
directly without having to call member methods of the Delegate class or the MulticastDelegate class. Through
some very simple examples, I'll show how delegates are used, both in Managed C++ and in C#.

Basic operations

Declaring delegates

In Managed C++ we use the __delegate keyword to declare delegates. In C# we use the delegate keyword. In
both cases the compiler will automatically inherit from System::Delegate. There is no difference in the manner
of declaration between single-cast and multi-cast delegates. I presume that internally a single-cast delegate is
treated as a multi-cast delegate with just one encapsulated method.

//delegate declaration using Managed C++


__delegate String* DelegateAbc();
//delegate declaration using C#
public delegate String DelegateAbc();

Binding delegates to methods

For a single-cast delegate we simple use the default delegate constructor which the delegates inherit from
System::Delegate. The constructor takes two arguments, where the first argument is the object whose method
we are binding to the delegate and the second argument is the address of the method. For static methods the
first argument can be 0. In C# things are simplified further in that we don't need to pass the first argument. The
C# compiler figures it out for us.
//binding delegates using MC++
DelegateAbc *d1 = new DelegateAbc(t1,&Test::TestAbc); //instance method
DelegateAbc *d2 = new DelegateAbc(0,&Test::TestStatic); //static method
//binding delegates using C#
DelegateAbc d1 = new DelegateAbc (t1.TestAbc); //instance method
DelegateAbc d2 = new DelegateAbc (Test.TestAbc); //static method

For multi-cast delegates we use the Delegate.Combine method which has two overloads. One overload takes an
array of Delegate objects and combines them. The other overload takes two Delegate objects and combines
them. Both return a Delegate object which we need to cast to our delegate type. Again, C# programmers have
it really easy. The + and += operators has been overloaded in C# and adding a delegate to another delegate is
done simply by using the + operator on any number of delegates.

//multi-cast delegate using MC++


d1 = static_cast<DelegateAbc*> (Delegate::Combine(d1,
new DelegateAbc(t1,&Test::TestAbc)));
//multi-cast delegate using C#
d1 = d2 + new DelegateAbc (Test.TestAbc); //using the + operator
d1 += new DelegateAbc (Test.TestAbc); //using the += operator

For removing a delegate from the invocation list of a multi-cast delegate we use the Delegate.Remove method.
This method takes two arguments. The first argument is the source delegate which may contain one or more
encapsulated methods. The second argument is the delegate object that we wish to remove from the multi-cast
delegate. The method returns a Delegate object which we cast to the delegate type we are expecting. I guess
you might have guessed by now that C# would have a simpler way of doing things. In C# the - and -= operators
have been overloaded so that you can actually subtract a delegate from a multicast delegate.

//removing a delegate from a multi-cast delegate - MC++


d1 = static_cast<DelegateAbc*>(Delegate::Remove(d1,d2));
//removing a delegate from a multi-cast delegate - C#
d1 = d1 - d2; //using the - operator
d1 -= d3; //using the -= operator

Invoking a delegate

When we invoke a delegate, the encapsulated methods are synchronously called in the order in which they were
attached to the delegate. In Managed C++ this is achieved by calling a method called Invoke. This method is
added to our delegate class by the compiler and will have the same signature as our delegate. In C#, we need
not bother even this much, and all we have to do is to call a method that has the same name as our delegate
object, and pass it any required arguments. The Invoke mechanism described here is based on early binding. We
know exactly what the delegate signature is and thus we can invoke our delegate. It might interest you to know
that the Invoke method is actually added by the respective compilers and is not inherited from the Delegate
class. For late bound invocation you can use the DynamicInvoke method. But this article will not cover late
bound invocation as it's outside the scope and latitude of this article.

//invoking a delegate with MC++


d1->Invoke("4"); //passing a string as argument
d2->Invoke(); //no arguments
//invoking a delegate with C#
d1("4"); //passing a string as argument
d2(); //no arguments

Now we'll see some small sample programs that will make things clearer to you. Compile and run the programs
and try and figure out whether the output you get makes sense. If you are confused, don't worry too much, just
read the article once more and then think about it for some time. Things will slowly make sense. There are also
some good articles on MSDN dealing with delegates which will enlighten you further.

Program 1

In this program we'll see how to declare and use a single-cast delegate. Our delegate takes a String as
argument and returns a String as well. We'll first assign an instance method of an object to the delegate and
then invoke the delegate. Then we'll assign a static method of a class to the same delegate object and again
invoke the delegate.

/* Managed C++ Sample */

#include "stdafx.h"
#using <mscorlib.dll>
using namespace System;

__delegate String* DelegateAbc(String* txt);

__gc class Test


{
public:
String* TestAbc(String* txt)
{
Console::WriteLine(txt);
return "Hello from TestAbc";
}
static String* TestStatic(String* txt)
{
Console::WriteLine(txt);
return "Hello from TestStatic";
}
};
int wmain(void)
{
Test *t1 = new Test();
DelegateAbc *d1 = new DelegateAbc(t1,&Test::TestAbc);
Console::WriteLine(d1->Invoke("First call"));
d1 = new DelegateAbc(0,&Test::TestStatic);
Console::WriteLine(d1->Invoke("Second call"));
return 0;
}
/* C# Sample */

using System;

class DelegateDemo
{
delegate String DelegateAbc(String txt);

public String TestAbc(String txt)


{
Console.WriteLine(txt);
return "Hello from TestAbc";
}
public static String TestStatic(String txt)
{
Console.WriteLine(txt);
return "Hello from TestStatic";
}
static void Main()
{
DelegateDemo t1 = new DelegateDemo();
DelegateAbc d1 = new DelegateAbc(t1.TestAbc);
Console.WriteLine(d1("First call"));
d1 = new DelegateAbc(DelegateDemo.TestStatic);
Console.WriteLine(d1("Second call"));

}
}

Program 2

Now we'll see an example of using a multi-cast delegate. Our delegate takes zero arguments and returns void.
We'll first create two single-cast delegates, one based on an instance method and the other one based on a
static method. Then we'll create our multi-cast delegate by combining the two delegates. Now we invoke our
multi-cast delegate. From the output you should be able to figure out the order in which the encapsulated
methods were called. Now we remove one of the delegates from our multi-cast delegate and again invoke it.
The output should match your understanding of the working of delegates.

/* Managed C++ Sample */

#include "stdafx.h"
#using <mscorlib.dll>
using namespace System;

__delegate void DelegateAbc();

__gc class Test


{
public:
void TestAbc()
{
Console::WriteLine("This is from TestAbc");
}
static void TestStatic()
{
Console::WriteLine("This is from the static method");
}
};
int wmain(void)
{
Test *t1 = new Test();
DelegateAbc *d1 = new DelegateAbc(t1,&Test::TestAbc);
DelegateAbc *d2 = new DelegateAbc(0,&Test::TestStatic);
d1 = static_cast<DelegateAbc*> (Delegate::Combine(d1,d2));
d1->Invoke();
d1 = static_cast<DelegateAbc*>(Delegate::Remove(d1,d2));
Console::WriteLine();
d1->Invoke();
return 0;
}
/* C# Sample */

using System;

class DelegateDemo
{
delegate void DelegateAbc();

public void TestAbc()


{
Console.WriteLine("This is from TestAbc");
}
public static void TestStatic()
{
Console.WriteLine("This is from the static method");
}

static void Main()


{
DelegateDemo t1 = new DelegateDemo();
DelegateAbc d1 = new DelegateAbc(t1.TestAbc);
DelegateAbc d2 = new DelegateAbc(DelegateDemo.TestStatic);
d1 = d1+d2;
d1();
d1 -= d2;
Console.WriteLine();
d1();
}
}

Program 3

In this program we will see how we can pass a delegate object as an argument to a method. The groovy thing
about this is that the called method has absolutely no idea what the passed delegate is referencing. In our little
example we have a delegate that takes an int and returns an int. We'll write two methods that can be assigned
to the delegate, one that returns the square of the passed number and the other that returns the cube of the
passed number.

/* Managed C++ Sample */

#include "stdafx.h"
#using <mscorlib.dll>
using namespace System;

__delegate int DelegateAbc(int);

__gc class Test


{
public:
int SquareMe(int i)
{
return i*i;
}
int CubeMe(int i)
{
return i*i*i;
}
void ShowResult(DelegateAbc* d, String* s,int i)
{
Console::WriteLine("{0} of {1} is {2}",s,
i.ToString(),d->Invoke(i).ToString());
}
};
int wmain(void)
{
Test *t = new Test();
t->ShowResult(new DelegateAbc(t,&Test::SquareMe),"Square",7);
t->ShowResult(new DelegateAbc(t,&Test::CubeMe),"Cube",7);
}
/* C# Sample */

using System;

class DelegateDemo
{
delegate int DelegateAbc(int i);

public int SquareMe(int i)


{
return i*i;
}
public int CubeMe(int i)
{
return i*i*i;
}
void ShowResult(DelegateAbc d, String s,int i)
{
Console.WriteLine("{0} of {1} is {2}",s,i,d(i));
}

static void Main()


{
DelegateDemo t = new DelegateDemo();
t.ShowResult(new DelegateAbc(t.SquareMe),"Square",7);
t.ShowResult(new DelegateAbc(t.CubeMe),"Cube",7);
}
}

Conclusion

Well, summing up, a delegate is just about the equivalent of function pointers except that delegates are objects
and are type safe. Unlike function pointers delegates can reference both static and instance methods of a class.
Delegates inherit from MulticastDelegate. The compiler adds an Invoke method to your delegate object, which
has the same signature and return type as the delegate. Delegates can be single-cast or multi-cast. Multi-cast
delegates are formed by combining several delegates. Delegates can be passed as arguments to functions.

The great thing about delegates is that they don't care about the class whose member function they are
referencing. All it cares about is that the arguments passed and the return type match that of its own. We can
thus use delegates for black-box-invocation, where we don't know what member function the delegate is
pointing to. Delegates are very useful as event handlers. When an event is raised the event handlers of the
subscribing classes are invoked through delegates.

Difference b/w asp and asp dotnet

What is the difference between ASP and ASP.NET?

Web application development in .NET with ASP.NET has evolved a great deal. The overall architecture of web
applications in .Net is much more improved and robust. The enhanced features in ASP.NET make it the best
available technology for web application development. The code behind the ASP.Net scripts can be in written in
any .Net compliant programming language.

The script (ASP.NET scripts), logic (code behind) and presentation (view) are separated from each other so they
may evolve independently. There are much more server controls now available in .Net including the standard
calendar and amazingly useful data grid controls. The ASP.Net web applications can now use .NET assemblies
and COM components to serve the client requests. ASP.NET pages are now compiled contrary to the ASP pages
which are interpreted by the ISA server. Truly speaking, there is no comparison between ASP and ASP.NET...
ASP.NET simply rules!

………………………….

The differences between C# and VB.NET


48818 Users read it.
George Petrov
(June 13, 2002)
Rati 243 3.1 out
ng: users of 5
Question:
What are the differences between C# and VB.NET, and which language should I use to create my ASP.NET Web
pages?

Answer:

by Scott Michell

With ASP.NET, developers can choose to create the server-side code for their Web pages in a myriad of
languages. The most common languages that developers will choose, will likely be VB.NET or C#. (There are a
number of other languages one can choose to use, from Perl.NET to JScript.NET to COBOL.NET.) Of the many
ASP.NET articles and code examples that exist on the Web, it seems that while a slim majority of them are
shown VB.NET, a good number are written in C#.

What language is the "best" language choice? If you are a VB wizard, should you take the time to learn C# or
continue to use VB.NET? Are C# ASP.NET pages "faster" than VB.NET ASP.NET pages? These are questions that
you may find yourself asking, especially when you're just starting to delve into .NET. Fortunately the answer is
simple: there is no "best" language. All .NET languages use, at their root, functionality from the set of classes
provided by the .NET Framework. Therefore, everything you can do in VB.NET you can do in C#, and vice-a-
versa. The only differences among languages is merely a syntactical one.

If you are more familiar with Java, JScript, or C/C++, you may find C#'s syntax more familiar than VB.NET's. If
you've been doing VB for the past five years, there's no reason to think you have to now switch to a new
langauge (although you should always look to be learning new things).

What if you have an ASP.NET Web page written in C# that you want to convert to VB.NET, or vice-a-versa? As
aforementioned, the languages only differ in their syntax, so this translation, while not usually trivial, is still
fairly striaghtforward, and can be accomplished systemmatically. For information on the syntactical differences
between the two languages, be sure to read: From VB.NET to C# and Back Again.

……………..

The differences between C# and VB.NET


48818 Users read it.
George Petrov
(June 13, 2002)
Rati 243 3.1 out
ng: users of 5
Question:
What are the differences between C# and VB.NET, and which language should I use to create my ASP.NET Web
pages?

Answer:

by Scott Michell

With ASP.NET, developers can choose to create the server-side code for their Web pages in a myriad of
languages. The most common languages that developers will choose, will likely be VB.NET or C#. (There are a
number of other languages one can choose to use, from Perl.NET to JScript.NET to COBOL.NET.) Of the many
ASP.NET articles and code examples that exist on the Web, it seems that while a slim majority of them are
shown VB.NET, a good number are written in C#.

What language is the "best" language choice? If you are a VB wizard, should you take the time to learn C# or
continue to use VB.NET? Are C# ASP.NET pages "faster" than VB.NET ASP.NET pages? These are questions that
you may find yourself asking, especially when you're just starting to delve into .NET. Fortunately the answer is
simple: there is no "best" language. All .NET languages use, at their root, functionality from the set of classes
provided by the .NET Framework. Therefore, everything you can do in VB.NET you can do in C#, and vice-a-
versa. The only differences among languages is merely a syntactical one.

If you are more familiar with Java, JScript, or C/C++, you may find C#'s syntax more familiar than VB.NET's. If
you've been doing VB for the past five years, there's no reason to think you have to now switch to a new
langauge (although you should always look to be learning new things).

What if you have an ASP.NET Web page written in C# that you want to convert to VB.NET, or vice-a-versa? As
aforementioned, the languages only differ in their syntax, so this translation, while not usually trivial, is still
fairly striaghtforward, and can be accomplished systemmatically. For information on the syntactical differences
between the two languages, be sure to read: From VB.NET to C# and Back Again.

………………..

Re: what is asp dotnet


Answ For beginners
er --------------
# 1 ASP.NET is a set of web development technologies marketed
by Microsoft. Programmers can use this set of technologies
to build web applications and XML web services.
For intermediate
----------------
This is the latest incarnation of Microsoft's middleware
for the Internet. ASP.NET is built upon the .NET Framework.
The .NET Framework has two main components: the common
language runtime (CLR) and the .NET Framework class
library. The CLR is the foundation of the .NET Framework.
You can think of it as an agent that manages code at
execution time for both Windows and ASP.NET applications.
The class library, the other main component of the .NET
Framework, is an object-oriented collection of reusable
components that you can use to develop applications for
both Windows and the Web. ASP.NET is therefore the required
environment that supports developers who use the .NET
Framework to develop Web-based applications.

…………….

ASP.NET (ASPDotNET)

Q13. How can you provide an alternating color scheme in a Repeater control?
Ans. Use AlternatintItemTemplate

Q14. Which two properties are on every validation control?


Ans. Control to Validate and Error Message.

Q15. What tag do you use to add a hyperlink column to the DataGrid?
Ans. < asp:HyperLinkColumn >

Q16. Which method is used to redirect user to another page without performing a round trip to the
client?
Ans. Server.transfer

Q17. How do you register JavaScript for webcontrols ?


Ans. use Attribtues.Add(scriptname,scripttext)

Q18. Which property on a Combo Box is set with a column name, prior to setting the DataSource, to
display data in the combo box?
Ans. DataTextField and DataValueField

Q19. Which control is used if you need to make sure if the values in two different controls
matched?
Ans. CompareValidator

Q20. Name the validation control available in asp.net?


Ans. RequiredField, RangeValidator,RegularExpression,Custom validator,compare Validator

Q21. What are the various ways of securing a web site to prevent from hacking ?
Ans.
1) Authentication/Authorization 2) Encryption/Decryption 3) Maintaining web servers outside the corporate
firewall. etc.,

Q22. Explain PostBack process?


Ans. PostBack is a process in which a Web page sends data back to the same page on the server.

Q23. What is the < machinekey > element and what two ASP.NET techniques in which it is used?
Ans. Configures keys to use for encryption and decryption of forms authentication cookie and view state data it
also verifies out-of-process session state

Two ASP.Net technique in which it is used are Encryption/Decryption & Verification

Q24. What is the difference between HTTP-Post and HTTP-Get?

Ans. Both sends parameters as name/value pairs in the HTTP request.

.,………………

Re: what's difference between Assembly and DLL?


"Steven Hsiao" <akina2k@hotmail.com> wrote in message <news:3b11b95c$1@news.devx.com>...

> I've read MS's .NET Framework FAQ,but I still can't understand what's difference
> between Assembly and DLL...Can someone help me?thanks

Assemblies are sagans of times easier to decompile. They cannot run on


any system without the .NyET run-time bloatware already installed. Who
knows how large it'll be compared to the MSVBVM*.DLLs. Updated versions
of the run-times will not replace older versions. DLL **** will go away
only to be replaced by DLL Stupidity, as each app might very well use a
different version of the run-times, as they mutate faster than VB4SP1
or perhaps the Access 2.0 Y2K patches. How soon we forget.

Diff b/w c and c#

What is really C# and not?

First of all C# is a programming language. It has a power to develop software. It is a strong language for
network and internet programming. C# has redefined the programming landscape. In addition, C# designed
with the need of C/C++ and Java programmers. Microsoft created it with Anders Hejlsberg the former Turbo
Pascal and Delphi luminary who was the most prominent Borland staff also Jbuilder team worked together with
him. This new language has been developed specifically with the .NET framework in mind, and as such is
designated to be the .NET developer's language of choice. One very important matter about C#, it is the first
component oriented programming language. The hot topic at the moment though is not its relation to C/C++ or
Visual basic, but how it compares to Java and Delphi. Why Delphi? Because Anders has had a prime role during
C# developing. C# inherits some of it's characteristics from C++ and also is an object oriented language. C#
has the functionality of Java, Delphi and Visual Basic and it a very strong language. You can not reject Delphi
similarity because theoretically Borland was trying to do the same thing with Borland C++ Builder working on
Delphi. But C# has the most functionality of Java and C++ and theoretical similarity with Delphi and Visual Basic
to use this Java and C++ functionality in a RAD environment. You may remember properties term from both
Delphi and Visual Basic. On the other hand, when I read "C# combines the high productivity of Microsoft Visual
Basic® with the raw power of C++" I quickly remember Borland's words for introduction to Borland C++ Builder.
What does all mean? C# is not a clone of Java. C# has more compatibility, functionality and similarity than Java.
Also, C# more similar to C++ as a programming language. C# stay much closer to C++.

Similarity and difference with C/C++


C# is directly related to C and C++. This is not just an idea, this is real. As you recall C is a root for C++ and
C++ is a superset of C. C and C++ shares several syntax, library and functionality. In addition structures,
unions, arrays, strings and pointers are most important and similar functionality for both languages. C# inherits
most of its operators, keywords, and statements directly from C++. Enums are clearly a meaningful concept in
C++. Finally I can clearly say that C# is the first component-oriented language in the C/C++ family. C#
constructors are very similar with C++ constructors. Like C++, methods are non-virtual by default, but can be
marked as virtual. There is also some difference between C# and C++, C# supports multiple inheritance of
interfaces, but not of classes. Another difference is destructors, their syntax is same with C++ but actually they
are very different.

Most of the C# basic types have the same names as C++ basic types but they are not really same. For example
a char in C# is equivalent to a wchar_t in C++. If you decide to move from C++ to C# there are a few things to
watch out to include the changes to new, structs, constructors, and destructors. Creating and using a
component (DLL) in C# is fairly easier than in C++. One more thing, Borland's C++ Builder was a pure C++
with simple RAD environment of Delphi and VB. C++ Builder was not a new language. This is one of the biggest
differences between C++ Builder and C#. The CLR (Common Language Runtime) improves runtime interactivity
between program development simplicity, security and portability. However CLR gives usability for cross-
language integration. In addition to all those CLL has+ a perfect foundation for a rich set of class libraries.

Conclusion

While there are a number of differences between C++ and C#, the syntax of C# is not very different from C++
and the transition to the new language is more easy with RAD environment of .NET. Also .NET's cross language
interoperability can give you the ability to use C++ and C# together Finally, if you want to use a strong
programming language like C++ with the simplicity of VB and Delphi, than you can use C# powered with CLR.

………………….

Some differences between C# and C++ - Entry 1

Up to chapter 8 now in my Visual C++ book. Here are some of the things I have learned so far:

• You declare the prototypes of your functions and member variables in a header file before you use them
(usually anyways).
• Your function code is in a source file (.cpp) with no class {} wrapping them (that is in the header file).
• In unmanaged C++ you use the keyword "delete" to clean up your objects when you are done with them.
• Managed classes are defined with __gc in front of them (ie. __gc class Foo {})
• In the header file, there is a section for different scoped items like (classes also end with a ";"):
• __gc class Foo {
• public:
• Foo();
• ~Foo();
• void SomeMethod();
• private:
• int SomeID;
• };

Instead of C#:

class Foo {
private int _someID;
public Foo()
{}
~Foo()
{}
public void SomeMethod()
{}
}

• It seems for strings you use "S" instead of "@" (ie. Console::WriteLine(S"Hello World"); instead of
Console.WriteLine(@"Hello World");), only noticed this through usage - not 100% sure if it is a 1-to-1
comparison on this one
• Unlike VB.Net and C#, C++ can force a Finalize by using the delete keyword, which will then call the
destructor and then the Finalize method
• Syntax for implementing an interface seems a little different - have to add "public"
• __gc class Tester : public IDisposable {
• }

…………………

This article points to the "Differences Between Microsoft Visual Basic .NET and Microsoft Visual C# .NET" white
paper.
Back to the top

MORE INFORMATION
Because of the previous differences between Visual Basic and C/C++, many developers assume incorrectly
about the capabilities of Visual Basic .NET. Many Visual Basic developers think that Visual C# is a more powerful
language than Visual Basic. In other words, Visual Basic developers assume that you can do many things in
Visual C# that you cannot do in Visual Basic .NET, just as there are many things that you can do in C/C++ but
cannot do in Microsoft Visual Basic 6.0 or earlier. This assumption is incorrect.

Although there are differences between Visual Basic .NET and Visual C# .NET, both are first-class programming
languages that are based on the Microsoft .NET Framework, and they are equally powerful. Visual Basic .NET is a
true object-oriented programming language that includes new and improved features such as inheritance,
polymorphism, interfaces, and overloading. Both Visual Basic .NET and Visual C# .NET use the common
language runtime. There are almost no performance issues between Visual Basic .NET and Visual C# .NET.
Visual C# .NET may have a few more "power" features such as handling unmanaged code, and Visual Basic .NET
may be skewed a little toward ease of use by providing features such as late binding. However, the differences
between Visual Basic .NET and Visual C# .NET are very small compared to what they were in earlier versions.

The "Differences Between Microsoft Visual Basic .NET and Microsoft Visual C# .NET" white paper describes some
of the differences between Visual Basic .NET and Visual C# .NET. However, remember that the .NET Framework
is intended to be language independent. When you must select between Visual Basic .NET and Visual C# .NET,
decide primarily based on what you already know and what you are comfortable with. It is easier for Visual Basic
6.0 developers to use Visual Basic .NET and for C++/Java programmers to use Visual C# .NET. The existing
experience of a programmer far outweighs the small differences between the two languages.

No matter which language you select based on your personal preference and past experience, both languages
are powerful developer tools and first-class programming languages that share the common language runtime
in the .NET Framework.

The following file is available for download from the Microsoft Download Center:
Download the "Differences between Microsoft Visual Basic .NET and Microsoft Visual C# .NET" white paper
package now. Release Date: June 18, 2002
For more information about how to download Microsoft Support files, click the following article number to view
the article in the Microsoft Knowledge Base:
119591 How to obtain Microsoft support files from online services
Microsoft scanned this file for viruses. Microsoft used the most current virus-detection software that was
available on the date that the file was posted. The file is stored on security-enhanced servers that help prevent
any unauthorized changes to the file.
Back to the top

……………..

C# is a managed language, e.g. the JIT compiler handles the conversion from High lvl code down into Native
Machine code where as C++ is unmanaged code. C# and C++ are night and day however, C# is a more high
lvl language and c++ is more a low lvl language.

However, C++ is not to be confused with C as they are both different languages C++ being a later dirivitive of
C.

It's C++ and C++ .NET.

C++ is an object oriented programming language, one of the most common programming
languages in use today.

.NET is a Microsoft programming framework that provides a library of classes that can be called
from C++ programs (and I believe programs in other languages, too) to do common programming
tasks.

……………..

Differences between C++ and C#

C# is a distinct language from C++. C++ is designed for general object oriented programming in the days when
the typical computer was a standalone machine running a command line-based user interface, C# is designed
specifically to work with the .Net and is geared to the modern environment of Windows and mouse-controlled
user interface, networks and the internet.

Microsoft has defined C# as follows:


"C# is a simple, modern, object oriented, and type-safe programming language derived from C and C++. C#
(pronounced 'C sharp') is firmly planted in the C and C++ family tree of languages, and will immediately be
familiar to C and C++ programmers. C# aims to combine the high productivity of Visual Basic and the raw
power of C++."

However it is also undeniable that the two languages are very similar in both their syntax and in that they are
both designed to facilitate the same paradigm of programming, in which code is based around hierarchies of
inherited classes.

Below I will briefly summarize the overall differences and similarities between the two languages. If you are a
C++ programmer, these points will give you the most important differences between the two languages at a
glance.

1. Environment
C++ was designed to be a low-level platform-neutral object-oriented programming language. C# was
designed to be a somewhat higher-level component-oriented language. The move to a managed
environment represents a sea change in the way you think about programming. C# is about letting go of
precise control, and letting the framework help you focus on the big picture.
With the managed environment of .NET, you give up that level of control. When you choose the type of
your object, the choice of where the object will be created is implicit. Simple types (int, double, and long)
are always created on the stack (unless they are contained within other objects), and classes are always
created on the heap. You cannot control where on the heap an object is created, you can't get its
address, and you can't pin it down in a particular memory location. (There are ways around these
restrictions, but they take you out of the mainstream.)
The very structure of C# reflects the underlying framework. There are no multiple inheritances and there
are no templates because multiple inheritances are terribly difficult to implement efficiently in a
managed, garbage-collected environment, and because generics have not been implemented in the
framework.

2. Compile Target
C++ code usually compiles to assembly language. C# by contrast compiles to Intermediate language
(IL), which has some similarities to java byte code. The IL is subsequently converted to native executable
code by a process of Just-In-Time compilation. The emitted IL code is stored in a file or a set of files
known as an assembly. An assembly essentially forms the unit, in which IL code id packaged,
corresponding to a DLL, or executable file that would be created by C++ compiler.

3. Memory Management
C# is designed to free the developers from the bookkeeping tasks to do with the memory management.
That means in C# you do not have to explicitly delete memory that was allocated dynamically on the
heap, as you could in C++. Rather, the garbage collector periodically cleans up memory that is no longer
needed.
Lets have two C++ variable declarations

int j = 30;
Myclass *pMine=new Myclass

Here the contents of j are stored on the stack. This is exactly that exists with C# value types. Our
Myclass instance is, however stored on the heap, and the pointer to it is on the stack. This is basically the
situation with C# reference type, except that in C# the syntax dresses the pointer up as a reference. The
equivalent of C# is:

Int j=30;
Myclass mine=new Myclass()

This code has pretty much the same effect in terms of where the objects are stored as does the above
C++ code - the difference is that Myclass is syntactically treated as a reference rather then a pointer.
The big difference between C++ and C# is that C# doesn't allow you to choose how to allocate memory
for a particular instance. For example, in C++ you wished to do this:

Int* pj=new int(30);


Myclass Mine; dfd

This will cause the int to be allocated on the heap, and the Myclass instance to be allocated on the stack.
You can't do this in C# because C# deems that an int is a value type while any class is always a
reference type.
The other difference is that there is no equivalent to C++'s delete operator in C#. Instead, with C#, the
.Net garbage collector periodically comes in and scans through the refrences in your code in order to
identify which areas of the heap are currently in use by our program. It is then automatically able to
remove all the objects that are no longer in use. This technique effectively saves you from having to free
up nay memory yourself on the heap.
4. Program Flow
Program flow is similar in C# to C++. In particular, the following statements works exactly the same way
as they do in C++ and have the same syntax :

For, Return, Goto, Break, Continue


New in C# : foreach

There are couple of syntactical differences for the if, while, do...while and switch statements and C#
provides an additional control flow statement; foreach

5. If …. Else Condition
if statement works exactly the same way and has exactly the same syntax in C# as in C++, apart from
one point. The condition in each if and else clause must evaluate to a bool. For example, assuming x is
an integer data types, not a bool, the following C++ code would generate a compilation error in C#

if(x)
{…}

The correct syantax in C#

If(x != 0)
{…}

This shows that how additionally type safety in C# traps error early.
While and do …while

Int x;
While(x) //wrong
While(x != 0) //OK

Just as for if, these statements have exactly syntax and purpose in C# as they do in C++, except that
the condition expression must evaluate to a bool.

6. Switch
the switch statement server the same purposes in C# as it does in C++. It is however; more powerful in
C# since you can use a string as the test variables, something that is not possible in C++.
In C# a switch statement may not "fall through" to the next statement if it does any work. Thus, while
the following is legal in C++, it is not legal in C#:

switch (i)
{
case 4:
CallFuncOne();
case 5: // error, no fall through
CallSomeFunc();
}

To accomplish this, you need to use an explicit goto statement:


switch (i)
{
case 4:CallFuncOne();
goto case 5;
case 5:
CallSomeFunc();
}

If the case statement does not work (has no code within it) then you can fall through:

switch (i)
{
case 4: // fall through
case 5: // fall through
case 6:
CallSomeFunc();
}

7. New control flow statement- “foreach”


C# provides an additional flow control statement, foreach. Foreach loops across all items in array or
collection without requiring explicit specification of the indices.
Syntax:

Foreach(double someElement in MyArray)


{
Console.WriteLine(someElement);
}
8. Boxing
In some cases you might wish to treat a value type as if it was a refrence type. This is achived by a
process know as boxing.
Syntactically this just means casting the variable to an object.

Int j = 10;
Object boxobj = (object) j;

Boxing acts like any other cast, but you should be aware that it means the contents of the variables will
be copies to the heap and a reference created.
The usual reason for boxing a value in order to pass it to a method that expects a erfrence type as a
parameter. You can also unbox value, simply by casting it back to its original type.

Int j = 10;
Object boxobj = (object) j;
Int k = (int) boxobj;

The process of unboxing will raise an exception if you attempt to cast to the wrong type and no cast is
available for you to do the conversion.

9. Structs
Structs are significantly different in C#. In C++ a struct is exactly like a class, except that the default
inheritance and default access are public rather than private. In C# structs are very different from
classes. Structs in C# are designed to encapsulate lightweight objects. They are value types (not
reference types), so they're passed by value. In addition, they have limitations that do not apply to
classes. For example, they are sealed, which means they cannot be derived from or have any base class
other than System.ValueType, which is derived from Object. Structs cannot declare a default (parameter
less) constructor.

10. Value Types and reference types


C# distinguishes between value types and reference types. Simple types (int, long, double, and so on)
and structs are value types, while all classes are reference types, as are Objects. Value types hold their
value on the stack, like variables in C++, unless they are embedded within a reference type. Reference
type variables sit on the stack, but they hold the address of an object on the heap, much like pointers in
C++. Value types are passed to methods by value (a copy is made), while reference types are effectively
passed by reference.
11. Classes
Classes in C# follow much the same principles as in C++, though there are a few differences in both
features and syntax.

Class MyClass : MyBaseClass


{
Private string SomeFiels;
Public in SomeMethod()
{
Return 2;
}
}

Classes defined in C# using what at first sight looks like much the same syntax as in C++, but there are
numerous differences:
a. There is no access modifier on the name of the base class. Inheritance is always public
b. A class can only be derived from one base class. If no base class is explicitly specified, then the
class will automatically be derived from System.Object, which will give the class all the
functionality of System.Object, the most commnly used of which is ToString().
c. In C++, the only types of class members are variables, functions, constructors, destructors and
operator overloads, C# also permits delegates, events and properties.
d. The access modifiers public, private and protected have the same meaning as in C++ but there
are two additional access modifiers available:
i. Internal
ii. Protected internal
e. C++ requires a semicolon after the closing brace at the end of a class definition. This is not
required in C#.

12. Destructors
C# implements a very different programming model for destructors to C++.This is because the garbage
collection mechanism in C# implies that:
a. There is less need for destructors, since dynamically allocated memory will get removed
automatically.
b. Since it is not possible to predict when the garbage collector will actually destroy a given object, if
you do supply a destructor for a class, it is not possible to predict precisely when that destructor
will be executed.

Because memory is cleaned up behind the scenes of C#, you will find that only a
small proportion of your classes actually require destructors. C# has two-stage
destruction mechanism:
• The class should derive from IDisposable interface and implements Dispose () method.
• The class should separately implements at destructor, which is viewed as a reserve mechanism in
case a client doesn't need to call Dispose()

C#'s destructor looks, syntactically much like a C++ destructor, but it is totally
different. The C# destructor is simply a shortcut for declaring a Finalize method that chain up to its base
class. Thus writing
~MyClass()
{
// do work here
}
is identical to writing
MyClass.Finalize()
{
// do work here
base.Finalize();
}

13. Virtual methods must be explicitly overridden


In C# the programmer's decision to override a virtual method must be made explicit with the override
keyword.
To see why this is useful, assume that a Window class is written by Company A, and that List Box and
Radio Button classes were written by programmers from Company B using a purchased copy of the
Company A Window class as a base. The programmers in Company B have little or no control over the
design of the Window class, including future changes that Company A might choose to make.
Now suppose that one of the programmers for Company B decides to add a Sort method to ListBox:

public class ListBox : Window


{
public virtual void Sort() {"}
}

This presents no problems until Company A, the author of Window, releases version 2 of its Window
class. It turns out that the programmers in Company A also added a Sort method public class Window:

public class Window


{
// "
public virtual void Sort() {"}
}
In C++ the new virtual Sort method in Windows would now act as a base method for the virtual Sort
method in ListBox. The compiler would call the Sort method in ListBox when you intend to call the Sort in
Window. In C# a virtual function is always considered to be the root of virtual dispatch, that is, once C#
finds a virtual method, it looks no further up the inheritance hierarchy If a new virtual Sort function is
introduced into Window the run-time behavior of ListBox is unchanged. When ListBox is compiled again,
however, the compiler generates a warning:
"\class1.cs(54,24): warning CS0114: 'ListBox.Sort()' hides inherited member 'Window.Sort()'.

To make the current member override that implementation, add the override keyword. Otherwise add the
new keyword.
To remove the warning, the programmer must indicate what he intends. He can mark the ListBox Sort
method new, to indicate that it is not an override of the virtual method in Window:

public class ListBox : Window


{
public new virtual void Sort() {"}
}

This action removes the warning. If, on the other hand, the programmer does want to override the
method in Window, he need only use the override keyword to make that intention explicit.
14. C# requires definite assignment
C# requires definite assignment, which means that the local variables, age, ID, and yearsServed must be
initialized before you call GetStats. This is unnecessarily cumbersome; you're just using them to get
values out of GetStats. To address this problem, C# also provides the out keyword, which indicates that
you may pass in uninitialized variables and they will be passed by reference. This is a way of stating your
intentions explicitly:

public class MyClass


{
public void GetStats(out int age, out int ID, out int yearsServed) { ….. }
}

Again, the calling method must match.

MyClass.GetStats(out age,out ID, out yearsServed);

15. Boolean Values Conversion


There is no conversion between the bool type and other types (specifically int).
C# Boolean values can not be treated as integer
If you write a code like this
if(BoolReturnFunction()) {}
and check if it returns zero it will evaluate flase and otherwise true

However using assignment versus equality is not allowed ,if you write:

if( x = 4 ) {}

Where x is Boolean type variable, it will give you an compile error


Constant value '4' cannot be converted to a 'bool'

If you write like this:


if(Convert.ToInt32(x)=4) {}
it will give you compilation error
Cannot implicitly convert type 'int' to 'bool'

16. Exceptions
Exceptions are used in the same way in C# as in C++, apart from the following two differences:
• C# defines the finally block, which contains code that is always executed at the end of try block
irrespective of whether any exception was thrown. The lack of this feature in C++ has been a
common cause of complaint among C++ developers. The finally block is executed as soon as
control leaves a catch or try block, and typically contains cleanup code for resources allocated in
the try block.
• In C++, the class thrown in the exception may be any class. C#, however, requires that the
exception be a class derived from System.Exception.
C++ syntax for catch:

Catch (…) {}

C# syntax for catch:

Catch { }

The full syntax fro try..catch..finally in C# looks like this

Try {}
Catch (MyException e) {}
Finally {}

17. Delegates- Substitute of Pointer


C# does not support function pointers. However a similar effect is achieved by wrapping references to
methods in special forms of class know as delegates.
A delegate is a class that can hold a reference to a method. Unlike other classes, a delegate class has a
signature, and it can hold references only to methods that match its signature. A delegate is thus
equivalent to a type-safe function pointer or a callback.
Delegates can be passed around between methods, and used to call the methods to which they contains
reference, in the same way that function pointers can be in C++. Conceptually delegates can be used in
a similar way to an interface with a single method. The main practical difference is that with an interface
the method name is fixed, whereas with a delegate only the signature is fixed - the method name can be
different

// delegate declaration
delegate void MyDelegate(int i);
class Program
{
public static void Main()
{
TakesADelegate(new MyDelegate(DelegateFunction));
}

public static void TakesADelegate(MyDelegate SomeFunction)


{
SomeFunction(21);
}

public static void DelegateFunction(int i)


{
System.Console.WriteLine("Called by delegate with number: {0}.", i);
}
}

Output: Called by delegate with number: 21.

18. Properties
Most C++ programmers try to keep member variables private. This data hiding promotes encapsulation
and allows you to change your implementation of the class without breaking the interface your clients
rely on. You typically want to allow the client to get and possibly set the value of these members,
however, so C++ programmers create accessor methods whose job is to modify the value of the private
member variables.
In C#, properties are first-class members of classes. To the client, a property looks like a member
variable, but to the implementor of the class it looks like a method. This arrangement is perfect; it allows
you total encapsulation and data hiding while giving your clients easy access to the members.
Properties are defined with property declarations. The first part of a property declaration resembles a
field declaration. The second part includes a Get accessor and/or a Set accessor. In the example below, a
class Employee defines a property Age.

public class Employee


{
private static int age;
public int Age
{
get{ return age; }
set {age= value;}

}
}

19. Attributes and Metadata.


One significant difference between C# and C++ is that C# provides inherent support for metadata: data
about your classes, objects, methods, and so forth. Attributes come in two flavors: those that are
supplied as part of the CLR and attribute you create for your own purposes. CLR attributes are used to
support serialization, marshaling, and COM interoperability. A search of the CLR reveals a great many
attributes. As you've seen, some attributes are applied to an assembly, others to a class or interface.
These are called the attribute targets.
Attributes are applied to their target by placing them in square brackets immediately before the target
item. Attributes may be combined, either by stacking one on top of another.

[assembly: AssemblyDelaySign(false)]
[assembly: AssemblyKeyFile(".\\keyFile.snk")]

or by separating the attributes with commas.

[assembly: AssemblyDelaySign(false),
assembly: AssemblyKeyFile(".\\keyFile.snk")]

Custom Attributes - Custom attributes are user-defined attributes that provide additional information
about program elements. For example, you might define a custom security attribute that specifies the
permissions required by the caller to execute a procedure.

[AttributeUsage(AttributeTargets.All)]
public class DeveloperAttribute : System.Attribute
{
private string name;
public DeveloperAttribute(string name)
{
this.name = name;
}

public virtual string Name


{
get {return name;}
}
}

You can apply this attribute in the following way:

[Developer("Joan Smith")]

Conclusion
While there are a number of subtle traps waiting for the unwary C++ programmer, the syntax of C# is
not very different from C++ and the transition to the new language is fairly easy. The interesting part of
working with C# is working your way through the new common language runtime library, which provides
a host of functionality that previously had to be written by hand. This article could only touch on a few
highlights. The CLR and the .NET Framework provide extensive support for threading, marshaling, Web
application development, Windows-based application development, and so forth.
The distinction between language features and CLR features is a bit blurry at times, but the combination
is a very powerful development tool.

Differences Between VB.NET / C#

"....Because of the past differences between Microsoft® Visual Basic, Microsoft® Visual CT, and Microsoft®
Visual C++, many developers have the impression that Microsoft® Visual C# .NET is a more powerful language
than Microsoft® Visual Basic .NET. Some developers assume that many things that are possible in Visual C#
.NET are impossible in Visual Basic .NET, just as many things that are possible in Microsoft® Visual CT 6.0 and
earlier or Microsoft® Visual C++T 6.0 and earlier are impossible in Microsoft® Visual BasicT 6.0 and earlier. This
assumption is incorrect. Although differences exist between Visual Basic .NET and Visual C# .NET, they
are both first-class programming languages that are based on the Microsoft® .NET Framework, and
they are equally powerful..."

Re: Difference between C++ and C#.net


Answer Default access Specifier is Public in c++. 0 Sivaram
#3 Default access Specifier is Private in c#.net. an.s

Re: Difference between C++ and C#.net


Answer c++:
#4 1. C++ code usually compiles to assembly language.
2. will allow multiple inheritence. eg. allows a method to
be overriden many times in subclasses (derived classes).

C#:
1. C# by contrast compiles to Intermediate language (IL),
which has some similarities to java byte code.
2. supports inheritence, but not multiple, only 1 override
per method/function/

S-ar putea să vă placă și