The type T must be a reference type in order to use it as parameter while using interface

I got the error for the below code

public static Moq.Mock<T> CreateInstanceOfIMock<T>() {
    return new Moq.Mock<T>();
}

I have solved the error it by using referred class type. See this below code

public static Moq.Mock<T> CreateInstanceOfIMock<T>() where T : class
{
    return new Moq.Mock<T>();
}

Now I want to move this var mockColorsRepository = new Moq.Mock<IColorsRepository>(); code into common code by using generics. here IColorsRepository is an interface. So I made an interface reference for T instead of class like this below code

public static Moq.Mock<T> CreateInstanceOfIMock<T>() where T : interface
{
    return new Moq.Mock<T>();
}

But am getting The type T must be a reference type in order to use it as parameter error. How can I refer interface instead of class to T. How can I achieve this?

Jon Skeet
people
quotationmark

There's no generic constraint in C# to enforce that a type argument is an interface. But where T : class is really "where T is a reference type" - it includes interfaces.

If you wanted to enforce that T is an interface rather than a class, you could perform an execution-time check using typeof(T) within the method, but in this case it sounds like you don't really need to constrain it to be an interface.

I'm not sure that the "helper" method is particularly useful though - if you compare:

var mock = Helper.CreateInstanceOfIMock<Foo>();

and

var mock = new Moq.Mock<Foo>();

or even (unless you have Mock<T> as another type somewhere) just a using Moq; directive and

var mock = new Mock<T>();

The latter seems just as readable and shorter... it makes sense if you're going to add more logic in your method, but if it's only ever going to call the constructor, I don't think I'd bother with it.

people

See more on this question at Stackoverflow