13

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?

2
  • 3
    You almost definitely shouldn't be using a struct in the first place. Commented Jul 3, 2011 at 18:22
  • Is there a compelling reason this cannot be defined as a class instead? Commented Jul 3, 2011 at 18:36

4 Answers 4

19

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#)

Sign up to request clarification or add additional context in comments.

Comments

6

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

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.
4

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

3

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.