Arunprasanth K V
Arunprasanth K V

Reputation: 21921

Access a static class member using a string variable ( string holds the name of static class)

I am confused about is there any way to access static class property values using the static class name defined inside a string variable Example :

I have a static class like below

public static class CoreConstants
{
    public const string  HostAddress= "someaddress";
}

And I have a string variable like

private string staticClassName="CoreConstants";

So is there any way to get the value of the HostAddress field using the string?

I know we can use Activator.CreateInstance() method if the class is a normal class , and using the instance we can get the values. But what about if the class is a static class ?

My real situation is like I have few static classes which holds constants for different language. Each request will pass a language indicator string, so using the string I need to get the exact message from the particular static class .

Upvotes: 2

Views: 2829

Answers (1)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

You first have to get the type the property belongs to:

var type = Type.GetType("CoreConstants");

Be aware that you need a fully qualified name, including the namespace and assembly the type is defined in. Otherwise the type-loader will just look in mscorlib making GetType return null.

If you have the type, simply call Type.GetProperty or Type.GetField depending on if it´s a field or a property you want to access:

var field = type?.GetField("HostAddress");

Finally get the value of the static field:

var value = field?.GetValue(null);

As your field is static, the paramater provided to GetValue is null. If it were an instance-field, you´d have to provide the instance.

Upvotes: 4

Related Questions