Sunday, June 26, 2011

Custom Events in C# - Basic Example

Creating custom events are very tough for me until i have started writing few custom events for my application. Here i wanted to share the way i have learned writing Custom Events. I hope, it will help the others too.

Before we go into the example, let me list out the concepts we need to know.

1. delegates, also called as function pointers

2.
event keyword

3. Event arguments

4. += and -= operators.

Thats it. We should know what are these and what functionality they provide.

A custom event can be implemented in 7 steps
1. Define event arguments , using which we can pass some information along with the event. Normally we have to create a class extending
EventArgs with required members. One of the best practice to suffix our class name with 'EventArgs', so that readability and maintainability will be more.

2. Create the Class on which you wanted to raise the event.

3. Define a delegate which will accept the event handler from the class which is intended to receive and handle this event. basically this delegate defines the signature of the event handler method that target application has to use.

4. create event member by using
event keyword and specify the event name. Whatever the name we uses here, will be visible to clients while adding the event handler.

5. Include the logic to call the event. Basically this part provides the link between event and it's handler. Based some condition(that's where event is raised) we will call event handler.

6. In client application, Add event handler using += operator. we can use -= operator to unregister the event.

7. Implement the event handler method to provide the logic that ehat should happen if the event fires.

Here is the Example,
Car Speed Controller Example. This is all about, if the car exceeds 60KMPH then warn the user saying Car speed is exceeding 60KMPH.

#Step1
Creating a class for passing event arguments.

//CarSpeedEventArgs.cs - Step 1
namespace CarSpeedControllerEvents
{
public class CarSpeedEventArgs
{
private string _message;

public CarSpeedEventArgs(string strMessage)
{
_message = strMessage;
}

public string Message
{
get
{
return _message;
}
}
}
}

//Car.cs
namespace CarSpeedControllerEvents
{
//Step 2
public class Car
{
private Int32 _CarSpeed;

public Car()
{
_CarSpeed = 0;
}

//Step 3
public delegate void CarSpeedController(object sender, CarSpeedEventArgs data);

//Step 4
public event CarSpeedController SpeedController;

public Int32 CarSpeed
{
set
{
_CarSpeed = value;

//Step 5
if (_CarSpeed > 60)
{
try
{
CarSpeedEventArgs objArgs = new CarSpeedEventArgs("Warning : Car speed exceeded 60KMPH");
SpeedController(this, objArgs);
}
catch { }
}
}
}

}
}

namespace CarSpeedControllerEvents
{
class Program
{
static void Main(string[] args)
{
Car myCar = new Car();

//Step 6 - Registering with event
myCar.SpeedController += ControlCalSpeed;

Console.WriteLine(" Car Current speed : 75KMPH");
myCar.CarSpeed = 75;
Console.WriteLine(" Car Current speed : 25KMPH");
myCar.CarSpeed = 25;
Console.WriteLine(" Car Current speed : 61KMPH");
myCar.CarSpeed = 61;

//Unregistering with event
myCar.SpeedController -= ControlCalSpeed;
Console.WriteLine(" Car Current speed : 81KMPH");
myCar.CarSpeed = 81;//This statement won't fire an event

Console.ReadLine();

}

//Step 7
public static void ControlCalSpeed(object sender, CarSpeedEventArgs data)
{
Console.WriteLine("\t ==> {0}", data.Message.ToString());
}
}
}

 

Wednesday, June 1, 2011

Managed Code vs Unmanaged Code

Managed code is not compiled to machine code but to an intermediate language which is interpreted and executed by some service on a machine and is therefore operating within a secure framework which handles very dangerous like memory and threads for you. In modern usage this frequently means .NET but does not have to.

In terms of .net, The code which is written using .net dlls and .net compliant languages such as C#, VB is called as Managed Code. Also we can say that, the code developed using .net framework is called as Managed Code. This code will be executed directly by CLR(Common Language Run time).

Managed code is what created using C#, VB and other .net compliant languages. Whatever the code you write, it will be converted an intermediate language after compilation. This intermediate code is called MSIL(Microsoft Intermediate Language) code. This compiled IL code will be copied to an assembly, kept ready for usage. You can't run this assembly with out the help of CLR. Because at run time CLR's JIT compilers will convert this code into Native Code, which can be executed by Operating System. You can simple drop this assembly in to any .net installed machine and start using it. The target machine's OS be anything, but it should have .net installed. So, that's why we say, .net can create portable applications.

Unmanaged code is compiled to machine code and therefore executed by the OS directly. It therefore has the ability to do damaging/powerful things Managed code does not. This is how everything used to work, so typically it's associated with old stuff like dlls

A programmer needs to write many common functions in an unmanaged code. So functions like garbage collecting, exception handling, etc have to be handled explicitly.The code, which is developed outside .NET Framework is known as unmanaged code.The code written in C/C++ etc is called as unmanaged code.it can't be run directly by CLR. But we can write some wrapper classes to run unmanaged code in CLR. These wrapper classes are 2 types CCW (COM Callable Wrapper) and RCW (Runtime Callabale Wrapper).

COM Callable Wrapper


Runtime Callable Wrapper

For more details on the image, please refer this post.

Sunday, May 29, 2011

Why doesn't C# support multiple inheritance?

This question is the one of the most frequently asked interview question. So lets see, what it is. Here is the answer i like the most found in Stack Overflow.

  • .NET was designed to support multiple languages, but not all languages can effectively support multiple inheritance. Or technically they could, but the complexities added in language semantics would make some of those languages more difficult to use (and less similar to their roots, like VB, and for backward compatibility reasons) and not worth the trade-off of being able to reuse code in the manner of multiple inheritance
  • It would also make cross-language library interoperability (via CLS compliance) less of a reality than it is today, which is one of the most compelling features of .NET. There are over 50 languages supported on .NET in over 70 implementations today
  • The most visible factor is language semantics complexity. In C++ we needed to add explicit language features in order to address ambiguities (such as the classic diamond problem) caused by multiple inheritance, such as the "virtual" keyword to support virtual inheritance to help the compiler resolve inheritance paths (and we had to use it correctly too)
  • As we know code is written 20% of the time, but read 80% of the time. Thus advocates on simplicity side prefer not to add language features for the sake of keeping semantics simple. In comparison C# code is significantly simpler to read than C++ code, and arguably easier to write