Compiler Warning (level 1) CS1720
Expression will always cause a System.NullReferenceException because the default value of 'generic type' is null
If you write an expression involving the default of a generic type variable that is a reference type (for example, a class), this error will occur. Consider the following expression:
default(T).ToString()
Since T
is a reference type, its default value is null, and so attempting to apply the ToString method to it will throw a NullReferenceException.
The class reference constraint on type T
ensures that T
is a reference type.
The following sample generates CS1720.
// CS1720.cs
using System;
public class Tester
{
public static void GenericClass<T>(T t1) where T : class
{
Console.WriteLine(default(T).ToString()); // CS1720
}
public static void Main() {}
}
.NET feedback
.NET is an open source project. Select a link to provide feedback: