EN VI

C# - How can I use an array value to build a reference to Settings?

2024-03-11 03:30:04
C# - How can I use an array value to build a reference to Settings?

Say I have some values in my program's Settings file

ClassLibrary.Properties.Settings.Default.SettingName1
ClassLibrary.Properties.Settings.Default.SettingName2
ClassLibrary.Properties.Settings.Default.SettingName3

and I have a method in which I want to get a Settings value based on some incoming integer value. Is there a way that I can concatenate the incoming integer and the name to make the assignment? I know I can just create a concat string, but is there a way to use that resulting string to get the value from the specified Setting?

In other words, just because I can do this
string combinedPath = "ClassLibrary.Properties.Settings.Default.SettingName" + (string)intValue;

The combined result is only a string, so I can't do this:

var mySettingsValue = combinedPath;

Is there a way to use that concatenated string to reference the object to which it points?

Solution:

If you need to map strings to objects, you can use a Dictionary<string, object> or similar data structure. Here’s an example:

Dictionary<string, object> dict = new Dictionary<string, object>();

dict["ClassLibrary.Properties.Settings.Default.SettingName1"] = new MyObject();

string combinedPath = "ClassLibrary.Properties.Settings.Default.SettingName" + (string)intValue;
if (dict.ContainsKey(combinedPath))
{
    MyObject obj = dict[key] as MyObject;
    // Now you can use obj
}

(In C#, you cannot directly use a concatenated string to reference an object. This is because C# is a statically typed language, and variable names are resolved at compile time, not at runtime.)

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login