0

I need to create a dll file which contains all the interfaces of the classes but doesn't contain any class. Because I use these interfaces for a lot of classes it's must be like that:

public interface IClassA
{
    string Word { get; }
}

public interface ITest<TClassA> where TClassA : IClassA
{
    TClassA A { get; }
}

Example of two classes that implements these interfaces the way I want:

public class ClassA : IClassA
{
    public string Word
    {
        get;
        private set;
    }

    public string Sentence
    {
        get;
        private set;
    }

    public ClassA(string word, string sentence)
    {
        this.Word = word;
        this.Sentence = sentence;
    }
}

public class Test : ITest<ClassA>
{
    public ClassA A
    {
        get;
        private set;
    }

    public Test(ClassA a)
    {
        this.A = a;
    }
}

And I want to do something like that in the main program:

public static void Main(string[] args)
{
    ClassA a = new ClassA("hey", "hey world!");
    Test t = new Test(a);

    Print((ITest<IClassA>)t);        
}

public static void Print(ITest<IClassA> t)
{
    Console.WriteLine(t.A.Word);
}

But this casting: (ITest<IClassA>)t makes a run time error. How can I solve it? thanks!

2 Answers 2

3

You should declare Test as

public class Test : ITest<IClassA>

instead of ITest<ClassA>.

Or declare ITest<TClassA> to be covariant on TClassA:

public interface ITest<out TClassA> where TClassA : IClassA
Sign up to request clarification or add additional context in comments.

Comments

0

The Test-class implements the concrete ClassA (public class Test : ITest<ClassA>).

So you're trying to cast an ITest<ClassA> to ITest<IClassA> which obviously fails.

If you let the Test-class implement IClassA, the cast works:

public class Test : ITest<IClassA>
{
    public IClassA A
    {
        get; private set;
    }

    public Test(IClassA a)
    {
        this.A = a;
    }
}

2 Comments

I want the Test class to have a property of ClassA and not IClassA, It's not possible?
Yes, it is. Take a look @Thomas' answer: If ITest<TClassA> is covariant, it's possible: dotnetfiddle.net/KKkktG

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.