nelt22
nelt22

Reputation: 410

Right way to define interface type on class that contains a member of said interface type

I'm trying to figure out how to create an instance of a class which has a member that is an interface and somehow indicate that I want that member of that instance to be of certain class that implements the interface. I've been trying to use generics and other tricks but it's not working

namespace ConsoleApp1
{
    public class BaseClass<TGeneric> where TGeneric : Interface
    {
        public TGeneric member;

        public BaseClass() {
            member = new Implementation1(); //Getting an error here :(
        }
    }

    public interface Interface
    {
        void sayHello();
    }

    public class Implementation1 : Interface
    {
        public void sayHello() {
            Console.WriteLine("interface 1");
        }
    }

    public class Implementation2 : Interface
    {
        public void sayHello() {
            Console.WriteLine("interface 2");
        }
    }

    class Program
    {

        static void Main(string[] args) {
            BaseClass<Implementation1> b = new BaseClass<Implementation1>();
            b.member.sayHello();
            Console.Read();
        }

    }
}

Cheers!

Upvotes: 1

Views: 30

Answers (1)

Loocid
Loocid

Reputation: 6451

Imagine if instead you defined b like so:

BaseClass<Implementation2> b = new BaseClass<Implementation2>();

Then obviously member = new Implementation1(); will fail because you're trying to assign an instance of Implementation1, to a member which is type Implementation2.

Instead you need to create a TGeneric and assign it to member:

member = new TGeneric();

This also requires you to change the base class signature to:

public class BaseClass<TGeneric> where TGeneric : Interface, new()

Alternatively you could have member be of type Interface, rather than TGeneric so the type is no longer concrete.

Upvotes: 2

Related Questions