Search code examples
c#generics.net-coreaction

Why i can not convert an object to a generic type


I have problem to undrestand this issue.

I have a generic Method that give an Action<T> to handle somthing. but i can not convert this object to T.

public interface T1 { }

public interface A : T1
{
    void A1();
}

public interface B : T1
{
    void A1();
}

public class Test : A, B
{
    void A.A1()
    {
        Console.WriteLine("A");
    }

    void B.A1()
    {
        Console.WriteLine(  "B");

    }

    public void T100<T>(Action<T> call) where T : T1
    {
        call((T)this); // error comes from here
    }
}

whats wrong with this code?

Please tell me how can i create somthing like above.


Solution

  • The error is due to the fact that the compiler does not guarantee that the cast will be done correctly and safely.

    You could use C# pattern matching :

    public void T100<T>(Action<T> call) where T : T1
    {
        if (this is T instance)
        {
            call(instance);
        }
        else
        {
    
        }
    }
    
    

    Usage :

    Test test = new Test();
    test.T100<A>(firstIstance=> firstIstance.A1()); // This will output "A"
    test.T100<B>(secondIstance => secondIstance.A1()); // This will output "B"