Say you have a class declaration, e.g.:
class MyClass
{
int myInt=7;
int myOtherInt;
}
Now, is there a way in generic code, using reflection (or any other means, for that matter), that I can deduce that myInt has a default value assigned, whereas myOtherInt does not? Note the difference between being initialised with an explicit default value, and being left to it's implicit default value (myOtherInt will be initialised to 0, by default).
From my own research it looks like there is no way to do this - but I thought I'd ask here before giving up.
[Edit]
Even with nullable and reference types I want to distingush between those that have been left as null, and those that have been explicitly initialised to null. This is so that I can say that fields with an initialiser are "optional" and other fields are "mandatory". At the moment I'm having to do this using attributes - which niggles me with their redundancy of information in this case.
May be this is not the simplest solution...
You can use de DefaultValue attribute to set the value like:
Import System.ComponentModel and System.Reflection
And then recover the default value with reflection:
This approach uses the property get/set process:
That's alot of code for one field - hello snippets!
If what you want is this, then check out the code at the bottom.
It's written in Oxygene[1], hope that's not a problem.
[1]or Delphi Prism how it's called now
Output:
A default value is a value like any other. There is no way to differentiate between these two cases:
In both cases, you give them the value 0, one way just saves you typing. There is no magic "default uninitialized value" - they are both zero. They work out to be exactly the same. However, the fact that you are even contemplating this indicates that you are seriously off the track of good ideas. What are you doing? What is your specific need? You are asking the wrong question ;)
Here's what I'd do if I wanted to build this as a general runtime feature. For scalar types, I'd create a default value attribute and use that to determine defaulticity.
Here's a partial solution to the task - I'm sure it could be better, but I just knocked it out:
Does the following help: