+ 3

Nullable int is value type or ref type ?

2nd Feb 2018, 1:32 PM
manish balwani
2 Réponses
+ 9
int is actually struct and structures are value types, while object (class) are reference types (Integer)
2nd Feb 2018, 1:35 PM
Vukan
Vukan - avatar
0
I'd say that it's a reference type, as a nullable type is indeed an object. In fact, int? x = 10; and Nullable<int> x = 10; These two declarations are the same. You can see that using the '?' operator is just a shorthand for declaring a Nullable<T> object (which allows the data to be null), and so it is passed by reference, as all objects are passed by reference. If you just need to pass the value, tho, you can use the value property of the variable. int? x = 10; // This is an object // This property accesses the Nullable's // value directly, so you can use it to // to pass 10 (in this case) by value x.Value Just remember that, as the nullable can be null, you need to check if it has or not a value before passing it. You can do this using the HasValue property. ... { int? x = null; // My method is not called if (x.HasValue) MyMethod(x.Value); x = 10; // My method is called, and 10 is // passed by value if (x.HasValue) MyMethod(x.Value); } ... void MyMethod (int x) { DoStuffWith(x); }
24th Apr 2018, 7:51 PM
Mante
Mante - avatar