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.
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".
In C# a struct is a 'value type', which can't be null.
A struct can be either passed/returned by value or passed/returned by reference (via a pointer) in C.
1) To check if the structure is empty:fmt. Println( "It is an empty structure." ) fmt. Println( "It is not an empty structure." )
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With