Defining a struct actually defines two types: a value type, and a class type which derives from System.ValueType
. If a request is made to create a variable, parameter, field, or array (collectively, 'storage location') of a type which derives from System.ValueType, the system will instead create a storage location which will store the object's fields rather than storing a reference to an object in which those fields appear. On the other hand, if a request is made to create an instance of a type deriving from System.ValueType, the system will create an object instance of a class which derives from System.ValueType.
This may be demonstrated by creating a struct which implements IValue:
interface IValue {int value {get; set;}};
struct ValueStruct : IValue
{
public int value {get; set;}};
}
with generic test routine and code to wrap it:
static void Test<T>(T it) where T:IValue
{
T duplicate = it;
it.value += 1;
duplicate.value += 10;
Console.WriteLine(it.value.ToString());
}
static void Test()
{
ValueStruct v1 = new ValueStruct();
v1.value = 9;
IValue v2 = v1;
Test<ValueStruct>(v1);
Test<ValueStruct>(v1);
Test<IValue>(v1);
Test<IValue>(v1);
Test<IValue>(v2);
Test<IValue>(v2);
}
Note that in every case, calling GetType on the parameter passed to Test would yield ValueStruct, which will report itself as a value type. Nonetheless, the passed-in item will only be a "real" value type on the first two calls. On the third and fourth calls, it will really be a class type, as demonstrated by the fact that a change to duplicate
will affect it
. And on the fifth and sixth calls, the change will be propagated back to v2, so the second call will "see" it.
obj == null ||
will return true for reference types.default(T) != null
will return false for theNullable<T>
structs. – Viscountcyobj != null ||
will return true for non-null reference-type objects. – ViscountcyNullable<T>
objects.int? bar = null;
Pass that through the function, you get false. (Didn't expect that, to be honest.) – Viscountcyreturn obj == null ? false : ...
still presents a problem forNullable<T>
. – Viscountcy