Reputation: 386
Suppose I have the following method:
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void EmptyMethod<T>(T inputVariable) where T: parentType
{
if(typeof(T) is childType)
{
// do something
}
if(typeof(T) is anotherChildType)
{
// do other things
}
}
I'm using this method in different places of the program, but when I check MSIL of release build I see following things: 1. The method is not inlined. 2. But what's worse - the method evaluates the type of the inputVariable during runtime (that is expected - see this link https://learn.microsoft.com/en-us/dotnet/csharp/pattern-matching).
But I'd like to have this method inlined and the type of the inputVariable to be evaluated during compile time.
Upvotes: 2
Views: 406
Reputation: 239684
Checking the MSIL is irrelevant to inlining since that's done by the JIT - the second compilation phase for .NET code.
MSIL still contains generic code that doesn't know what types it will be used with. This is why .NET generics can work across compilation units.
It does look strongly like this shouldn't be generic code at all but two overloads with the same method name:
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void EmptyMethod(childType inputVariable)
{
// do something
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void EmptyMethod(anotherChildType inputVariable)
{
// do other things
}
If you find yourself doing type checks inside your generic code, that's usually a sign that you've picked the wrong tool for the job.
Upvotes: 3