Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create structure with null value support?

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?

like image 373
Hamed Avatar asked Jul 03 '11 18:07

Hamed


People also ask

Can structure have null values?

However, since structs are value types that cannot be null , the default value of a struct is the value produced by setting all value type fields to their default value and all reference type fields to null .

How do you assign a structure to null?

You cannot ask your struct type to set that pointer to null by itself. You will have to do it explicitly every time you create an object of type struct stack , e.g. struct stack my_stack = { 0 };

What is the null value of a struct?

A Null value means that the value of a field, variable or parameter is undefined. Variables and parameters are implicitly initialized to Null when they are declared. For String or Struct data types, Uniface provides some special handling.

Can structs be null C++?

Struct fields, like columns of primitive types, can have null values.


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

like image 51
MrWednesday Avatar answered Sep 19 '22 17:09

MrWednesday


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

like image 23
ChaosPandion Avatar answered Sep 20 '22 17:09

ChaosPandion