1

I am trying to create class called Stats that uses generic parameter T. I intend to use T as int? or float?. However, when I try to create object of class Stats I get that: Error 1 The type 'int?' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method .... Any help would be appreciated

Here's my code:

Stats<int?> stats = new PlayerMatchStats(); // PlayerMatchStats inherits Stats


public abstract class Stats<T> : BaseEntity where  T : struct 
{

}
caked bake
  • 327
  • 2
  • 6
  • 14

2 Answers2

4

From the C# programming guide, when a generic constraint of where T : struct is specified "the type argument must be a value type. Any value type except Nullable can be specified."

You can make a member of a generic class with a struct constraint nullable, e.g.

public class Foo<T> where T : struct
{
   public T? SomeValue { get; set; }
}

but you cannot provide a nullable as the closed generic type.

Preston Guillot
  • 6,493
  • 3
  • 30
  • 40
1

where T : struct does not allow nullable types. Perhaps this refactoring is what you're after:

public abstract class Stats<T> where T : struct
{
    // instead of the following with T being int?
    // public abstract T Something { get; }
    // have the following with T being int
    public abstract T? Something { get; }
}
public class PlayerMatchStats : Stats<int> { ... }

// this is now valid:
Stats<int> stats = new PlayerMatchStats();

Or remove the struct constraint:

public abstract class Stats<T>
{
    public abstract T Something { get; }
}
public class PlayerMatchStats : Stats<int?>
{
    public override int? Something { get { return 0; } }
}

Stats<int?> stats = new PlayerMatchStats();
Tim S.
  • 55,448
  • 7
  • 96
  • 122