I'm new in C#. In c# I can't set value of a structure to null how can I create a structure with null value support?
- 3You almost definitely shouldn't be using a struct in the first place.SLaks– SLaks2011-07-03 18:22:35 +00:00Commented Jul 3, 2011 at 18:22
- Is there a compelling reason this cannot be defined as a class instead?juharr– juharr2011-07-03 18:36:31 +00:00Commented Jul 3, 2011 at 18:36
4 Answers
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#)
Comments
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.
1 Comment
Nullable<T> isn't just compilermagic. It's supported by CLR magic too. For example a null nullable boxes to the real null.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 Comments
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.