I want to test whether a variable of unknown type has been assiged a non-default
value.
The variable is probably a struct type, so I can't solve this with where T : class
.
The struct's IEquatable<T>
implementation will usually assume that its fields have been assigned to already, so I can't use EqualityComparer<T>.default
, or else it will crash with a null pointer exception.
(Yes, I'm being careful to ensure that the 0 value for a struct is not ever treated as a valid value, so I'm sure I can treat it specially.)
I'm willing to turn on /unsafe
to accomplish this. I would like to be able to write the body to this function:
unsafe static bool UnsafeIsDefault<T>(T a) {
// Error: Operator '==' cannot be applied to operands of type 'T' and 'T'
// return a == default(T);
// Real body goes here
}
I realize that another solution would be to constrain where T : ICheckForDefault
with interface ICheckForDefault { bool IsDefault(); }
, and write an implementation of that for every type I intend to use here, but I was hoping to avoid that.