S. Lorétan a écrit :
I have some structs in different namespaces/classes/other structs and I
sometime have to check if it contains something or not.
myStruct == null doesn't work.
Value types (structs) cannot be null, they are always instanciated. By
the way, you are not checking if your instance contains something, you
are checking if your instance is ... instanciated.
I've currently done it by creating a IsNull method in my structs:
struct TestStruct {
public int Value;
public bool IsNull() {
return this.Equals(new TestStruct());
}
}
Is this correct? Is there another way?
As for this example, new TestStruct() creates an instance of TestStruct
with all its fields initialized with their default type value. For an
int (which is a value type), that is 0.
The default implementation of Equals for a value type uses reflection to
check fields equality. So in this case, IsNull will return true if Value
equals 0. I cannot assert the correctness of this behaviour.
Another way ? If your classes may not be instanciated, use reference
types (classes) instead of value types. In .NET 2.0, you could also use
the Nullable<Tclass.
Or have your value type manage its null state. I would have it this way :
interface INullable {
bool IsNull {
get;
}
}
struct TestStruct: INullable {
private int _Value;
private bool _IsNull;
public TestStruct(int value) {
Value=value;
}
public int Value {
get {
if (_IsNull)
throw new InvalidOperationException();
return _Value;
}
set {
_Value=value;
_IsNull=false;
}
}
public bool IsNull {
get {
return !_IsNull;
}
}
}
Mathieu