The type must be a reference type in order to use it as parameter 'T' in the generic type or method

C#Generics

C# Problem Overview


I'm getting deeper into generics and now have a situation I need help with. I get a compile error on the 'Derived' class below as shown in the subject title. I see many other posts similar to this one but I'm not seeing the relationship. Can someone tell me how to resolve this?

using System;
using System.Collections.Generic;


namespace Example
{
    public class ViewContext
    {
        ViewContext() { }
    }

    public interface IModel
    {
    }

    public interface IView<T> where T : IModel 
    {
        ViewContext ViewContext { get; set; }
    }

    public class SomeModel : IModel
    {
        public SomeModel() { }
        public int ID { get; set; }
    }

    public class Base<T> where T : IModel
    {

        public Base(IView<T> view)
        {
        }
    }

    public class Derived<SomeModel> : Base<SomeModel> where SomeModel : IModel
    {

        public Derived(IView<SomeModel> view)
            : base(view)
        {
            SomeModel m = (SomeModel)Activator.CreateInstance(typeof(SomeModel));
            Service<SomeModel> s = new Service<SomeModel>();
            s.Work(m);
        }
    }

    public class Service<SomeModel> where SomeModel : IModel
    {
        public Service()
        {
        }

        public void Work(SomeModel m)
        {

        }
    }
}

C# Solutions


Solution 1 - C#

I can't repro, but I suspect that in your actual code there is a constraint somewhere that T : class - you need to propagate that to make the compiler happy, for example (hard to say for sure without a repro example):

public class Derived<SomeModel> : Base<SomeModel> where SomeModel : class, IModel
                                                                    ^^^^^
                                                                 see this bit

Solution 2 - C#

You get this error if you have constrained T to being a class

Solution 3 - C#

If you put constrains on a generic class or method, every other generic class or method that is using it need to have "at least" those constrains.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChrisSView Question on Stackoverflow
Solution 1 - C#Marc GravellView Answer on Stackoverflow
Solution 2 - C#thekipView Answer on Stackoverflow
Solution 3 - C#GuishView Answer on Stackoverflow