19.9.12

Reviewing CLR via C# by Jeffrey Richter

Lately, I finished reading "CLR via C#" by Jeffrey Richter. This 5-star book was very beneficial to me and I thought it would also add value for every .NET developer.

Not only does the book give you a good insight on the features of the framework, but it also digs deep into the inner working of the CLR giving the reader a great knowledge on how to write code that runs under the .NET framework.

The book analyses how the CLR handles our code, how and when it gets converted into intermediate language, how it gets executed and -more importantly- how the developer can interfere with this behavior and get the best out of the framework.

Furthermore, the book explores the fundamentals of the framework; including data types, methods, events, interfaces, generics ... etc. These are the basics of the framework that we all know about but the book explains them in detail so you learn what to use when.

The author, who has extensive experience in the framework since its beginnings, puts the picture clear to the reader about what features of the framework are better be avoided and which of them should be used with caution. Not all features are made for all scenarios!

On the other hand, the book introduces some features that we rarely use or might not know about at all. It also illustrates the best way of using some features that we're familiar with in order to shorten our tasks or make our code more efficient and reliable.

In brief, I think this is a must-read book by every .NET developer.

13.6.12

Difference Between Events And Delegates in C#

It might be the syntax of C# that provides us with shortcuts to write delegates and events that causes this confusion.

In short, a delegate is a class that contains a field that holds a reference to a method and then you can call the method with appropriate parameters. Whereas an event is a variable that you can define and specify one or more delegates to be added to it.

Let's go through these examples to simplify and illustrate the idea.

class Program
{
  static void Main(string[] args)
  {
    DelegatesAndEvents obj = new DelegatesAndEvents();
    obj.Execute();
  }
}


public class DelegatesAndEvents
{
  public delegate void MyDelegate(int val);

  internal void Execute()
  {

    MyDelegate d = new
    MyDelegate(this.MyMethod);

    int val = 15;

    d.Invoke(val);
  }

  void MyMethod(int val)
  {
    Console.WriteLine(val);
    Console.ReadLine();
  }
}


In the previous code, I create a delegate type and name it MyDelegate. This delegate type is designed to call methods that take one parameter of type integer. What actually happens behind the scenes is that the CLR creates a class called MyDelegate and this class would have some fields and a method called Invoke. The invoke method takes one parameter of type integer.

In the execute method, I create an instance of the delegate (recall that a delegate is a class and I can create instances from it like any other class). The constructor of this MyDelegate takes one parameter of type integer. However, what I actually pass to the constructor is the name of the method I want to invoke and it will implicitly understand that I'm passing a reference to the method.

Another point that is worth mentioning is that I could have invoked the method without using the Invoke method. This is just a syntactical shortcut provided by C#. It would be like this:
d(val);


Now let's change our code a little bit. (comment added to show added, removed and changed code)
public class DelegatesAndEvents
{

  public delegate void MyDelegate(object sender, EventArgs e); // Changed

  internal void Execute()
  {

    MyDelegate d = new
    MyDelegate(this.MyMethod);

    EventArgs e = new EventArgs(); // Added
    object sender = 15; // Added

    d(sender, e); // Changed
  }

  void MyMethod(object sender, EventArgs e)
  {
    Console.WriteLine(sender);
    Console.ReadLine();
  }
}


What I did is just changing the parameters that MyDelegate is designed to take. Instead of taking one parameter of type integer, it now takes 2 parameters of types object and EventArgs, respectively. There's no big deal so far.

Now I will introduce an event and see how to use it. I will change the code a little bit. (comment added to show added, removed and changed code )

public class DelegatesAndEvents
{

  public delegate void MyDelegate(object sender, EventArgs e);
  public event MyDelegate MyEvent; // Added

  internal void Execute()
  {

    MyDelegate d = new MyDelegate(this.MyMethod);

    object sender = 15;
    EventArgs e = new EventArgs();

    MyEvent += new MyDelegate(d); // Added

    MyEvent(sender, e); // Added

    //d(sender, e);  Removed
  }


  void MyMethod(object sender, EventArgs e)
  {
    Console.WriteLine(sender);
    Console.ReadLine();
  }
}


Here's what I did in the last code change.I declared an event of type MyDelegate. In other words, I created an event that can hold delegates of type MyDelegate, so in the future I can use this event to invoke methods with the signature MyDelegate defines (methods that take 2 parameters of type object and EventArgs). And then,instead of invoking MyMethod directly using the delegate, I use the newly created event MyEvent to invoke the method.

As you can see, MyEvent is just a holder of delegates. I can add delegates to this event by using += syntax and passing the delegate instance in the constructor. I can add more than one delegate instance to this event. Look at the following code. (comment added to show added, removed and changed code )

public class DelegatesAndEvents
{

  public delegate void MyDelegate(object sender, EventArgs e);
  public event MyDelegate MyEvent;

  internal void Execute()
  {

    MyDelegate d = new MyDelegate(this.MyMethod);

    object sender = 15;
    EventArgs e = new EventArgs();

    MyDelegate d2 = new MyDelegate(this.MyMethod2); // Added

    MyEvent += new MyDelegate(d);
    MyEvent += new MyDelegate(d2); // Added

    MyEvent(sender, e);
  }

  void MyMethod(object sender, EventArgs e)
  {
    Console.WriteLine(sender);
    Console.ReadLine();
  }

  // This method is added
  void MyMethod2(object sender, EventArgs e)
  {
    Console.WriteLine(sender);
    Console.ReadLine();
  }
}

Instead of adding a delegate instance to the event the normal way, There's a syntax shortcut provided by C# that looks like this:
MyEvent += MyMethod;


So I can change my code to look like this: (comment added to show added, removed and changed code )

class DelegatesAndEvents
{

  public delegate void MyDelegate(object sender, EventArgs e);
  public event MyDelegate MyEvent;

  internal void Execute()
  {      

    //MyDelegate d = new MyDelegate(this.MyMethod);  Removed

    object sender = 15;
    EventArgs e = new EventArgs();

    //MyDelegate d2 = new MyDelegate(this.MyMethod2);  Removed

    MyEvent += MyMethod; // Changed
    MyEvent += MyMethod2; // Changed

    MyEvent(sender, e);
  }

  void MyMethod(object sender, EventArgs e)
  {
    Console.WriteLine(sender);
    Console.ReadLine();
  }


  void MyMethod2(object sender, EventArgs e)
  {
    Console.WriteLine(sender);
    Console.ReadLine();
  }
}


Notice that I no longer need to create delegate instances because the new syntax will implicitly create it.

Finally, let me introduce EventHandler, which is a delegate type itself. You can type EventHandler in your code in Visual Studio and press F12 to discover this.

namespace System
{

  [Serializable]
  [ComVisible(true)]
  public delegate void EventHandler(object sender, EventArgs e);

}


As you can see, EventHandler is a delegate type designed to invoke methods that take 2 parameters, object and EventArgs, exactly like MyDelegate that I defined in the previous code. Therefore, I can replace MyDelegate with EventHandlerand everything will be the same. The final code will be like this:

class DelegatesAndEvents
{    

  //public delegate void MyDelegate(object sender, EventArgs e);  Removed
  public event EventHandler MyEvent; // Changed

  internal void Execute()
  {
    object sender = 15;
    EventArgs e = new EventArgs();

    MyEvent += MyMethod;
    MyEvent += MyMethod;

    MyEvent(sender, e);
  }


  void MyMethod(object sender, EventArgs e)
  {
    Console.WriteLine(sender);
    Console.ReadLine();
  }


  void MyMethod2(object sender, EventArgs e)
  {
    Console.WriteLine(sender);
    Console.ReadLine();
  }
}


Normally, you don't go through all of the previous steps. You only see the last portion of code. All I was trying to do is to show you how this last code came.

now I hope it became clear that delegates are just types that you can create instances from. All delegates inherit from the classMulticastDelegate which is used to invoke other methods according to what we define. Events are meant to hold one or more delegate instance and once you raise the event, it invokes all the methods attached with those delegate instance.

8.6.12

Confusion when Passing Reference Type Objects in C#

Everybody knows that when making a method call in C#, reference type objects are passed by reference. In other words, whatever changes you make to your object in the called method will be reflected on the original one.

Let's examine the following code:

    class MyClass
    {
        public int MyInteger;
    }
    class Program
    {
        static void Main(string[] args)
        {
            MyClass myClass = new MyClass();
            myClass.MyInteger = 5;

            Console.Write("Value before method call: ");
            Console.WriteLine(myClass.MyInteger);
            MyMethod(myClass);
            Console.Write("Value after method call: ");
            Console.WriteLine(myClass.MyInteger);
        }            

        private static void MyMethod(MyClass myClass)
        {
            myClass.MyInteger = 10;
        }
    }
If you run the preceding code, it will show the following result:

Value before method call: 5
Value after method call: 10

This was expected. However, the idea that all reference type objects are passed by reference is not really accurate and the following proves so. If we change "MyMethod" by adding one line so it becomes as the following:
        private static void MyMethod(MyClass myClass)
        {
            myClass = new MyClass();
            myClass.MyInteger = 10;
        }

and then we run the program, guess what the result will be. The result will be as following:

Value before method call: 5
Value after method call: 5

The value of the field "MyInteger" did not change as you might expected. That is because what actually happens when you pass a reference type object to a method is that the reference to that object is copied and the copy is passed to the method. The new copy of the reference points to the same object, so if you make changes in the called method, you will be making changes on the same object. But if you create a new object in the called method, you will be actually changing the reference value that was passed and making it point to a new object. And whatever changes you make after this step will be irrelevant to the original object.

The following diagrams illustrates what happens in the previous 2 examples.

Example 1: What really happens when you pass an object
Example 1: What really happens when you pass an object

Example 2: Creating an instance inside the called method
Example 2: Creating an instance inside the called method



If you wish to make any changes to the object in the called method and have them all reflected on the original object even if you make a new instance in the called method, then what you need is to pass it by reference. You need to add the keyword ref before the object type in the method signature and also when calling the method. The code will look like this:

    class Program
    {
        static void Main(string[] args)
        {
            MyClass myClass = new MyClass();
            myClass.MyInteger = 5;

            Console.Write("Value before method call: ");
            Console.WriteLine(myClass.MyInteger);
            MyMethod(ref myClass);
            Console.Write("Value after method call: ");
            Console.WriteLine(myClass.MyInteger);
        }            

        private static void MyMethod(ref MyClass myClass)
        {
            myClass = new MyClass();
            myClass.MyInteger = 10;
        }
    }


25.4.12

Reference Type vs. Value Type in C#

Types in .NET Framework are either treated by Reference or by Value. Reference types variables are used by a reference (or a pointer) that points to their data. On the other hand, Value types variables are accessed directly through their values.

There are several differences between these 2 kinds of data types. I'll try here to highlight some of them throughout examples.

Reference Type variables are stored in the heap while Value Type variables are stored in the stack. This means that when a reference type variable is no longer used, it can be a candidate for garbage collection. However, a value type variable is removed from the memory once the method using it is over.

Reference types are typically declared using "class" keyword, while the value types are declared by the keyword "struct". Let's see an example of each.

    public class ReferenceType
    {
        public int Field { get; set; }        
    }  

    public struct ValueType
    {
        public int Field { get; set; }
    }

Let's now create a console application that uses the previous types.

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Reference Type");
            ReferenceType referenceType1 = new ReferenceType();
            ReferenceType referenceType2 = new ReferenceType();
            Console.WriteLine(referenceType1.Equals(referenceType2));
            
            Console.WriteLine("Value Type");
            ValueType valueType1 = new ValueType();
            ValueType valueType2 = new ValueType();
            Console.WriteLine(valueType1.Equals(valueType2));

            Console.ReadLine();
        }
   }


You might have expected that the first Console.WriteLine statement would print "true", but the actual result is "false". System.Object is considered the parent type of all other types and it has the method Equals and implements it in a way that doesn't care about the object's fields, but rather on its reference. However, all value types inherit from System.ValueType, which itself inherit from System.Object. System.ValueType overrides the implementation of Equals with a more logical one that depends on the values of object's fields.

Let's now have another example and see how reference types are considered equal.
 
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Reference Type");
            ReferenceType referenceType1 = new ReferenceType();
            ReferenceType referenceType2 = referenceType1;
            Console.WriteLine(referenceType1.Equals(referenceType2));

            Console.WriteLine("Value Type");
            ValueType valueType1 = new ValueType();
            ValueType valueType2 = valueType1;
            Console.WriteLine(valueType1.Equals(valueType2));

            Console.ReadLine();
        }
   }


Here, both of them print "true". The second Console.WriteLine statement obviously prints true because both objects have the save values for their fields. For the first statement, this explains to us the fact that reference types are used by their reference. In other words, when assigning "referenceType1" to "referenceType2", the CLR only copies referenceType1's reference and assigns it to referenceType2 so both of them become pointing to the same object data in the memory. Let's try the following to better illustrate the idea.

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Reference Type");
            ReferenceType referenceType1 = new ReferenceType();
            ReferenceType referenceType2 = referenceType1;

            Console.WriteLine(referenceType1.Field);

            referenceType2.Field = 5;

            Console.WriteLine(referenceType1.Field);


            Console.ReadLine();
        }
   }
Now you can see that although we didn't directly change the value of referenceType1, it has been changed because it points to the same data that referenceType2 points to. The following example illustrate the idea even more.

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Reference Type");
            ReferenceType referenceType = new ReferenceType();
            referenceType.Field = 1;
            Console.WriteLine("Before: " + referenceType.Field);
            Pass(referenceType);
            Console.WriteLine("After: " + referenceType.Field);

            Console.WriteLine("");
            Console.WriteLine("Value Type");
            ValueType valueType = new ValueType();
            valueType.Field = 1;
            Console.WriteLine("Before: " + valueType.Field);
            Pass(valueType);
            Console.WriteLine("After: " + valueType.Field);

            Console.WriteLine("");
            Console.WriteLine("Value Type By Reference");
            ValueType valueType2 = new ValueType();
            valueType2.Field = 1;
            Console.WriteLine("Before: " + valueType2.Field);
            Pass(ref valueType2);
            Console.WriteLine("After: " + valueType2.Field);


            Console.ReadLine();
        }

        static void Pass(ReferenceType referenceType)
        {
            referenceType.Field = 2;
        }



        static void Pass(ValueType valueType)
        {
            valueType.Field = 2;
        }


        static void Pass(ref ValueType valueType)
        {
            valueType.Field = 2;
        }

   }


Let's move now to another aspect of difference. Add the following 2 lines to the first example and then try to compile.
    
    Console.WriteLine(referenceType1 == referenceType2);
    Console.WriteLine(valueType1 == valueType2);

These 2 lines will not compile. You will get the compilation error message : "Operator '==' cannot be applied to operands of type 'MyNameSpace.ValueType' and 'MyNameSpace.ValueType".

Let's summarize and add some other differences in the following table.
Value Type Reference Type
Where are they stored in memory? Stack Heap
Parent Type System.ValueType System.Object
Inheritance All value types are sealed and you cannot inherit from other types You can normally inherit from other types
Access modifiers protected cannot be used Any access modifier can be used

27.3.12

Custom Validation Controls in ASP.NET

Validation controls in ASP.NET are great tools that reduce the time needed to do such a repetitive task> However, sometimes they don't provide all what we need. We still want to use them but we also want to add more validation that is custom to our business.

Custom Validation controls come to solve this problem. We can use them in conjunction with the normal Validation controls. We can provide either our custom client-side validation or server-side validation, or both.

In many times, we use custom validation controls to validate the entire logic of a form instead of a specific control. For this reason, we can leave the ControlToValidate property empty.

Here's a simple example of using custom validation controls. Suppose we have the following is the HTML:


<asp:Literal ID="lblMobileNumber" runat="server" Text="Mobile Number" />
<asp:TextBox ID="txtMobileNumber" runat="server" />

<asp:Literal ID="lblHomeNumber" runat="server" Text="Home Number" />
<asp:TextBox ID="txtHomeNumber" runat="server" />

<asp:Button runat="server" ID="btnSave" Text="Save" ValidationGroup="Save" />

And suppose that you want to force the user to enter either mobile number or home number, so you add the following custom control.

<asp:CustomValidator ID="cvMobileOrHomeNumber" runat="server" 
ErrorMessage="Please enter either mobile number or home number" ValidationGroup="Save"
ClientValidationFunction="validateMobileOrHomeNumber" 
OnServerValidate="cvMobileOrHomeNumber_ServerValidate" />



In ClientValidationFunction we specify the Javascript function to be executed for validation. This function should accept 2 parameters. The first parameter represents the source of the validation, and the second parameter is the one that we'll use to eventually decide whether the operation is valid or not. Let's create the function.
<script type="text/javascript">

    function validateMobileOrHomeNumber(source, args) {

        if (the operation is valild) {
            args.IsValid = true;
        }
        else {
            args.IsValid = false;
        }

        return;
    }

    </script>


Similarly, we use OnServerValidate to specify the method to be executed at server side. Let's see how to implement it.

protected void cvMobileOrHomeNumber_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if (the operation is valid)
                args.IsValid = true;
            else
                args.IsValid = false;
        }


That's it!

Popular Posts