+ 3
Nullable int is value type or ref type ?
2 ответов
+ 9
int is actually struct and structures are value types, while object (class) are reference types (Integer)
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);
}