#217 – T? Is Equivalent to Nullable<T>
January 20, 2011 Leave a comment
You can always use the form T?, rather than Nullable<T>, to declare a variable whose type is a nullable value type. The type T can be any built-in or custom value type.
This means that you can use this syntax for your own custom enum or struct types.
For example, if you have the following custom types:
public enum Mood { Crabby, Happy, Petulant, Elated } public struct Point3D { public float X, Y, Z; public string Name; public Point3D(float x, float y, float z, string name) { X = x; Y = y; Z = z; Name = name; } }
You can use the T? format as follows:
Mood? myMood = null; Mood mood2 = myMood ?? Mood.Elated; Point3D? somePoint = null; Point3D defaultPoint = new Point3D(0.0f, 0.0f, 0.0f, "Origin"); Point3D aPoint = somePoint ?? defaultPoint;