Home > Mobile >  How to cast a generic class on more generic types
How to cast a generic class on more generic types

Time:12-08

I've found only older answers to this question, that's why I try it again in the hope, that there is a solution.

I have a generic class that takes objects of classes which implement a specific interface. I can easily write a class implementing the interface on a variable of the type of this interface.

What I can't do is, creating a generic class that takes an instance of a class and write it on a variable of the same generic class that needs its class to only implement the interface.

public interface IBar {}

public class Foo : IBar {}

public class MyClass<T> where T : IBar 
{
    public T Value { get; set; }
}

// works 
IBar fooAsBar = new Foo();

// visual studio / compiler says no...
MyClass<IBar> classWithFooAsBar = new MyClass<Foo>();

Is there any way so I can convert MyClass in some way to MyClass? In the case were I need it, I only need to access the Value property and everything else does not matter for me.

CodePudding user response:

As the comments mentioned, it is basically not possible for goot reasons. What I did to achiv my goal was to create a wrapper class:

public interface IBar {}

public class Foo : IBar {}

public class MyClass<T> where T : IBar 
{
    public T Value { get; }
}

public class MyWrapper
{
    public IBar Value { get; }

    public MyWrapper(IBar myBar)
    {
        this.Value = myBar;
    }
}

// works 
IBar fooAsBar = new Foo();

// visual studio / compiler says yes...
MyWrapper classWithFooAsBar = new MyWrapper(new Foo());
IBar myBar = classWithFooAsBar.Value;
  • Related