Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can structs really not be null in C#?

Below is some code that demonstrates I cannot declare and initialize a struct type as null. The Nullable type is a struct, so why am I able to set it to null?

Nullable<bool> b = null; if (b.HasValue) {     Console.WriteLine("HasValue == true"); }  //Does not compile... Foo f = null; if (f.HasValue) {     Console.WriteLine("HasValue == true"); } 

Where Foo is defined as

public struct Foo {     private bool _hasValue;     private string _value;      public Foo(string value)     {         _hasValue = true;         _value = value;     }      public bool HasValue     {         get { return _hasValue; }     }      public string Value     {         get { return _value; }     } } 

The question has been answered (see below). To clarify I'll post an example. The C# code:

using System;  class Program {     static void Main(string[] args)     {         Nullable<bool> a;         Nullable<bool> b = null;     } } 

produces the following IL:

.method private hidebysig static void  Main(string[] args) cil managed {   .entrypoint   // Code size       10 (0xa)   .maxstack  1   .locals init ([0] valuetype [mscorlib]System.Nullable`1<bool> a,            [1] valuetype [mscorlib]System.Nullable`1<bool> b)   IL_0000:  nop   IL_0001:  ldloca.s   b   IL_0003:  initobj    valuetype [mscorlib]System.Nullable`1<bool>   IL_0009:  ret } // end of method Program::Main 

a and b are declared, but only b is initialized.

like image 631
Nate Avatar asked May 20 '11 20:05

Nate


People also ask

Can structs be null in C?

3 answers. It is not possible to set a struct with NULL as it is declared. Fila f = NUll; error: invalid initializer. So cast% from% to NULL , which is not even a type in this code, or assign Fila to a primitive type variable is "wrong".

Can a struct value be null?

In C# a struct is a 'value type', which can't be null.

Can struct be passed by value?

A struct can be either passed/returned by value or passed/returned by reference (via a pointer) in C.

How do I check if a struct is empty?

1) To check if the structure is empty:fmt. Println( "It is an empty structure." ) fmt. Println( "It is not an empty structure." )


1 Answers

The C# compiler provides you with a bit of sugar so you really are doing this:

Nullable<bool> b = new Nullable<bool>(); 

Here is the syntactic sugar

bool? b = null;     if (b ?? false)  {    b = true; } 
like image 102
ChaosPandion Avatar answered Sep 21 '22 22:09

ChaosPandion