THINK

that’s how i naturally know

Archive for February, 2011

C# Lambda Operator =>

leave a comment

Using a constructor as a delegate:

x => new MyClass(x);

if follows that this allows for C# generics to enable parameterized constructor of type T to be called within the generic class, thus bypassing the constraints.

Normally, one would delcare

public class MyClass<T> where T : new()
{
   // the above definition allows constructor call of
  void SomeFunction()
   {
       T myvar = new T();
   }
}

but if T does not have a parameterless constructor, then we can

public class MyClass<T>
{
     void SomeFunction(func<int, T> del)
      {
            int i = 10;
            T myvar = new del(i); // assume our constructor takes a single int as parameter
      }
}

and we invoke it by calling

myClass.SomeFunction(x => new apple(x));

Written by Jake

February 9th, 2011 at 12:28 pm

Posted in Programming

Tagged with ,