Let's assume I have a class ClassWithMember
class ClassWithMember
{
int myIntMember = 10;
}
How do I get the default value 10 of the myIntMember member by System.Type?
I'm currently struggling around with reflections by all I retreive is the default value of int (0) not the classes default member (10)..
You can simply provide a default value by writing an initializer after its declaration in the class definition. Both braced and equal initializers are allowed – they are therefore calle brace-or-equal-initializer by the C++ standard: class X { int i = 4; int j {5}; };
Just to clarify: all classes (including the ones you create) will default to null . Number value types will default to zero and structs are implementation defined (values are set in the constructor).
The variables of primitive type contains 0 as a default value in a broader sense. When variable is of any class type (non-primitive type), then it is known as reference variable, and it contains null value as a default value.
When we define a struct (or class) type, we can provide a default initialization value for each member as part of the type definition. This process is called non-static member initialization, and the initialization value is called a default member initializer.
You can try something like this:
var field = typeof(ClassWithMember).GetField("myIntMember",
BindingFlags.Instance | BindingFlags.NonPublic);
var value = (int)field.GetValue(new ClassWithMember());
The trick here is to instantiate an instance.
Try creating an instance an retreive the value with reflection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With