Search code examples
c#.netoptimizationdelegatescil

Whether the CIL code generated for a delegate type is compile time or runtime?


Lets say there is a delegate referring to two methods say Add() and Sub() . All i am asking is whether the C# compiler generates the equivalent IL code at runtime or at the compiletime ?

ex:

public int delegate Dele(int,int);

//methods
int Add(int a,int b)
{
    //...
}
int Sub(int a,int b)
{
    //...
}


//here comes the condition

if(cond)
{
   Del+=Add;
}
else
{
   Del+=Sub;
}

int ans=Del(4,4);

here whether the compiler generates the cil code for both true and false conditions at compiletime or runtime?


Solution

  • Which method is referred is only resolved when it invoked, i.e. at the runtime. In our case, yes it contributes a little for the optimization cause it had been invoked only once and there will be always only one CIL code in the execution path. Hope this is the answer you are looking for.