Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get default value of class member

Tags:

c#

default

member

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)..

like image 583
Ruben Aster Avatar asked Jun 07 '10 13:06

Ruben Aster


People also ask

How can we provide a default value for a member of a class?

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}; };

What is default value of class in C#?

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).

What is the default value of class variable in Java?

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.

Can C++ structs have default values?

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.


2 Answers

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.

like image 186
Anne Sharp Avatar answered Sep 29 '22 07:09

Anne Sharp


Try creating an instance an retreive the value with reflection.

like image 27
Henrik Gering Avatar answered Sep 29 '22 08:09

Henrik Gering