Jaa


C#2.0: Generic methods, delegates and type inference...

I did not like var in C# 3.0 because I felt it reduces code readability. For the same reason I do not like using Type-Inference in C# 2.0 generics.

 class MyClass{    public void MyMethod<T>(T value) {        Console.WriteLine("{0} {1}", typeof(T).FullName, 
                                     value.ToString());    }}class Program{    static void Main(string[] args)    {        MyClass mc = new MyClass();        mc.MyMethod(5);       // Type inference        mc.MyMethod<int>(12);  // Explicit type parameter    }}

Even though the first one using type inference requires less typing (and I'm sure will go a long way in CTS erradication) I prefer the more verbose explicit type parameter.

However when applied to generic delegates, type inference becomes a bit different. Consider the following

 class MyClass{    public delegate void Foo<T>(T item);    private void Bar(int i)    {        Foo <int > foo = MyMethod; // MyMethod<int> is inferred        //Foo foo = MyMethod<int>;    }    public void MyMethod<T>(T value)    {    }}

I was talking to a friend some-time back and when compared to generic methods, he had assumed that  type inference for generic delegate would mean that the type parameter of the delegate will be inferred. However as we see from the example above that the type of the delegate needs to be explictly given and from this the type of the generic method is inferred. I am kind of OK with this because at least the types are specified in the statement...

Comments

  • Anonymous
    March 02, 2006
    One of the blogs i've been reading a lot lately is I know the answer (it's 42). I've added it to my Reader...