Udostępnij za pośrednictwem


MSIL Trivia - 2 (Setters in C#)

Background: Let's create a setter in C# with a simple getter and setter...

using System;
class Employee
{
   private string name;
   public string Name
   {
      get
      {
         return name;
      }
      set
      {
         name=value;
      }
   }
}
class App
{
   public static void Main()
   {
      Employee e = new Employee();
      e.Name = "Rahul Soni";
      Console.WriteLine (e.Name);
   }
}

Question> What will happen if you use any other word than value in the code above?? We haven't declared it, but your compiler is still good with it. Do you know why?

Answer> Well, the answer lies in the way your C# compiles this code into MSIL. Let's have a look at MSIL...

image

Does it mean, that you can call this public method set_Name from your code directly instead of using e.Name above. Of course not!

Contrast this usage in VB...

Module Module1
    Private _name As String = String.Empty
    Public Property Name() As String
        Get
            Return _name
        End Get
        Set(ByVal val As String)
            _name = val
        End Set
    End Property
    Public Sub Main()
        Name = "Rahul Soni"
        Console.WriteLine(Name)
    End Sub
End Module

As you can see, in VB.NET you can use val instead of value and the MSIL would be generate appropriately.

image

So, why do you care to know about this little stuff? One reason I could think of is to ensure, that if you have a genuine curiosity... it will feel good to have it answered. I started as a VB.NET programmer and am comparatively new to C# and when I saw the setter using that value without declaring it, I was pretty confused :-) Wave

Cheers,
Rahul

Quote of the day:
Hard work never killed anybody, but why take a chance? - Edgar Bergen

Comments

  • Anonymous
    January 18, 2008
    PingBack from http://msdnrss.thecoderblogs.com/2008/01/19/msil-trivia-2-setters-in-c/

  • Anonymous
    January 21, 2008
    That's awesome! It's something I've always wondered about in the back of my mind, but never had the time to look into.  Being a "strict" guy, It made no sense to me to pass an undeclared variable and it seemed like a goofy place to require a constant.   Thanks!