-3

I'm trying to write some code to be as generic as possible, and as such want to make sure a function can alter the class's property in this manner:

public class Savesettings
{
    public int alpha, beta, gamma, up, down, right, left;

    public int MagicFunction(string value)

    {

    //if, say, the string is "alpha", return a reference to alpha etc...  

    }
}

Can I do this? I found Get name of property as a string but it's kinda too big brain for me. I think what I need is sorta like an inverse nameof, but that's not a very easy thing to search for apparently

EDIT: Sorry, I meant compile time.

Since it looks like what I asked for is impossible, can I instead use a public void MagicFunction(string value, int newvalue) to set the property?

AnProg
  • 43
  • 1
  • 6

1 Answers1

1

Why can't you use Dictionary ? Check following code:

public class Savesettings
{
    public Dictionary<string, int> sampleDictionay = new Dictionary<string, int>{
        {"alpha", 1},
        {"beta", 2},
        {"gamma", 3},
        {"up", 4},
        {"down", 5},
        {"right", 6},
        {"left", 7}
    };

    public int MagicFunction(string value)
    {
        if(sampleDictionay.ContainsKey(value))
            return sampleDictionay[value];      
        return 0;
    }
}

if you want to set the new value

public void MagicFunction(string value, int newValue)
{
    if(sampleDictionay.ContainsKey(value))
        sampleDictionay[value] = newValue;      
}
  • Your dictionary will never have any more than the default 7 objects? – Caius Jard Oct 23 '21 at 18:52
  • @CaiusJard For every instance of a class we will be having default 7 values. We can add values in the Dictionary using object instance; but it will only available to that particular object instance. On other hand, original question was having only these 7 properties so no point about discussing extra values in Dictionary. These solution will take care of original problem – Shreekesh Murkar Oct 24 '21 at 06:45
  • Where in the question did it imply that the dictionary could never have more values than those it was created with? I think I've missed that requirement – Caius Jard Oct 24 '21 at 06:49
  • @CaiusJard Original post has only 7 properties and there is no requirement that talks about adding new property at run time. We just wanted to fetch and update the property which is already present in the class. Using dictionary will solve our problem. Hope this helps – Shreekesh Murkar Oct 24 '21 at 06:55