For some general helper methods that I write, I would like to be able to call special processing when this value is the default value for my type. For reference types, this is easy - the default value is null . I cannot use a type parameter, although I could get around this.
I can do something like this:
public bool DetectPossiblyUninitializedValue(object val) { return val== null || val.GetType().IsValueType && Equals(val, Activator.CreateInstance(val.GetType()); }
This is what I'm using right now, but it depends on the implementation of Equals . It is beautiful, but not perfect. In particular, some implementations may override Equals to support more convenient semantics in common scenarios. Actually, it’s not uncommon to view the default value as special here, because it is inevitable in .NET due to default initialization.
However, in this case, I just want to know if the object was initialized, and therefore I do not want any user equality or anything else. Basically, I want to know if the memory area occupied by the structure is filled, zero as supporters of the virtual machine after initialization, and nothing more. In a sense, I'm looking for something similar to ReferenceEquals for structs: a comparison not related to the native implementation of the main object.
How to compare the original structure values without using Equals ? Can I compare the initial values of the structure in general?
Edit: I use this to connect classes + structures representing domain-specific concepts related essentially by arbitrary code representing various business rules for a graphical interface. Some old code essentially deals with possibly nested string dictionaries for arbitrary objects, which requires a bunch of untested throws or dynamic ; creating them are prone to errors. Therefore, it is nice to work with typed objects relatively directly. On the other hand, it is useful for the GUI and packaging code to handle possibly uninitialized values differently; and although in each case a type-by-type solution is possible, this is a lot of code; A reasonable default is helpful. In fact, I want the method to automatically generate a type identical to the other, but with all the properties / public fields extended to include the value “uninitialized”, but this is not a realistic function that can be expected - on the contrary, in a dynamic world this would be trivial achievable, although without any types elsewhere ...
Answers: Mehrdad sent a response to how to directly access structure bits ; I added an implementation using this to detect possibly uninitialized values .