How to create structure with null value support?
you can use Nullable<T>
for structs, or the shorthand form (?) of the same:
Represents an object whose underlying type is a value type that can also be assigned null like a reference type.
struct Foo
{
}
Nullable<Foo> foo2 = null;
Foo? foo = null; //equivalent shorthand form
Structs and value types can be made nullable by using the Generic Nullable<> class to wrap it. For instance:
Nullable<int> num1 = null;
C# provides a language feature for this by adding a question mark after the type:
int? num1 = null;
Same should work for any value type including structs.
MSDN Explanation: Nullable Types (c#)
You can use Nullable<T>
which has an alias in C#. Keep in mind that the struct itself is not really null (The compiler treats the null differently behind the scenes). It is more of an Option type.
Struct? value = null;
As @CodeInChaos mentions Nullable<T>
is only boxed when it is in a non-null state.
Nullable Types
Boxing Nullable Types
Since the "Struct" is not a reference type, you cannot assign "null" as usual manner. so you need to use following form to make it "nullable"
[Struct Name]? [Variable Name] = null
eg.
Color? color = null;
then you can assign null for the object and also check the nullability using conditional statements.