class Program
{
static void Main(string[] args)
{
Console.WriteLine(SomeFunction<int>()==null);
var temp = new SomeClass<int>();
Console.WriteLine(temp.SomeFunction() == null);
Console.ReadKey();
}
static public T? SomeFunction<T>() where T : struct
{
return null;
}
public class SomeClass<T> where T : struct
{
public T? SomeFunction()
{
return null;
}
}
}
In the above example, why does a nullable type need the struct constraint?
I don't understand why struct is the right syntax and not object or class.
Because Nullable<T> (or T?) also restricts T to be a struct.
So, for SomeFunction<T>'s generic type parameter T to fulfill Nullable<T>'s requirements, SomeFunction<T> must also declare the same constraints.
Here's another example of how constraints must be propagated:
interface ISomeInterface { }
class MyClass<T> where T: ISomeInterface { }
class Program
{
//MyClass's constaints must be "re-declared" here
public MyClass<T> SomeFunction<T>() where T : ISomeInterface
{
}
}
And why does Nullable<T> do that? Because a nullable reference type would make no sense. Refence types are already nullable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With