Frank Q.
Frank Q.

Reputation: 6592

Implementing a Generic Interface and a Non Generic Interface

I have two contracts (one Generic Interface and the other Non-Generic) as follows:

public interface IGenericContract<T>  where T : class
    {
        IQueryable<T> GetAll();
    }

public interface INonGenericContract
    {
        string GetFullName(Guid guid);
    }

I have a class implementing both

public class MyClass<T> :
        IGenericContract<T> where T : class, INonGenericContract
    {
        public IQueryable<T> GetAll()
        {
            ...
        }

        public string GetFullName(Guid guid)
        {
            ...
        }
    }

Everything is fine until this point when I compile it. But now when I try using this class I run into this error "error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'ConsoleApplication1.MyClass'. There is no implicit reference conversion from 'string' to 'ConsoleApplication1.INonGenericContract'."

class Program
    {
        static void Main(string[] args)
        {
            MyClass<string> myClass = new MyClass<string>(); //Error
        }
    }

If I do not implement the Non-generic contract it works fine. What could be wrong here ?

Thanks

Upvotes: 3

Views: 107

Answers (3)

Claudio Redi
Claudio Redi

Reputation: 68400

According what you show

public class MyClass<T> : IGenericContract<T> where T : class, INonGenericContract

T must implement INonGenericContract and string doesn't implement it. In short, string is not a valid parameter for class MyClass

If what you're looking for is implementing IGenericContract<T> AND INonGenericContract you should have

public class MyClass<T> : INonGenericContract, IGenericContract<T>

there is no need to have where T : class since IGenericContract<T> already has that constraint.

Upvotes: 2

Fredou
Fredou

Reputation: 20100

you are very close, what you have to do is implement the non generic interface, not put a constrain.

public class MyClass<T> :
    IGenericContract<T>, INonGenericContract where T : class
{
    public IQueryable<T> GetAll()
    {
        return null;
    }

    public string GetFullName(Guid guid)
    {
        return null;
    }
}

now you can do this

MyClass<string> myClass = new MyClass<string>(); 

Upvotes: 4

user4003407
user4003407

Reputation: 22122

In your code INonGenericContract is part of generic constraint, as it placed after where.

public class MyClass<T> :
    IGenericContract<T> where T : class, INonGenericContract

You likely want that:

public class MyClass<T> :
    IGenericContract<T>, INonGenericContract where T : class

Upvotes: 7

Related Questions