Home > Blockchain >  Generic method T type is the constraint type, not the real type of the passed object
Generic method T type is the constraint type, not the real type of the passed object

Time:04-08

I have this generic method with a constraint for ILogicPointContext. This method calls other generic methods with the same constraint, but the code throws exception since I need the type to be the correct one, not the interface type.

public void DoSomething<TContext>(TContext ctx)
    where TContext : ILogicPointContext
{
    var typeOfCtx = ctx.GetType();  // CcpContex
    var typeOfT = typeof(TContext); // ILogicPointContext
    ...

I have another similar method where the generic type of the method is the generic type of the object I pass to him and this works fine

private void InsertStepDefinition<TContext>(PipelineStepDefinition<TContext> stepInfo)
    where TContext : ILogicPointContext

In this case TContext is not the interface but the correct type.

What am I missing?

CodePudding user response:

The generic resolves automatically when called with variable types (not calling the method with <>).

Example:

void Main()
{
    Foo var1 = new Foo();
    ILogicPointContext var2 = var1;
    
    DoSomething(var1); //outputs Foo: generic resolution is automatically done on variable type
    DoSomething(var2); //outputs ILogicPointContext, for the same reason
}



interface ILogicPointContext{}
class Foo:ILogicPointContext{}

void DoSomething<TContext>(TContext ctx)
    where TContext : ILogicPointContext
{    
    Console.WriteLine(typeof(TContext).Name);
}

The second output is the actual type of TContext, the type the generic is 'created' with and is used within the method.

  • Related