Bob Gatto
Bob Gatto

Reputation: 131

Can a variable be used as a property?

I'm looking to do something like this:

string currPanel = "Panel";
currPanel += ".Visible"

Now at this point I have a string variable with the name of a property that only accepts Boolean values. Can I some how do something like this:

<data type> currPanel = true;

so the actual property Panel1.Visible accepts it without any errors?

Upvotes: 4

Views: 104

Answers (2)

user853710
user853710

Reputation: 1767

From what I can see here is that you are using WPF. Things like this you accomplish with converters

http://www.codeproject.com/Tips/285358/All-purpose-Boolean-to-Visibility-Converter

With MVVM and WPF you never need to do this

Upvotes: -1

xanatos
xanatos

Reputation: 111890

Supporting both properties and fields, but only instance ones:

public static void SetValue(object obj, string name, object value)
{
    string[] parts = name.Split('.');

    if (parts.Length == 0)
    {
        throw new ArgumentException("name");
    }

    PropertyInfo property = null;
    FieldInfo field = null;
    object current = obj;

    for (int i = 0; i < parts.Length; i++)
    {
        if (current == null)
        {
            throw new ArgumentNullException("obj");
        }

        string part = parts[i];

        Type type = current.GetType();

        property = type.GetProperty(part, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

        if (property != null)
        {
            field = null;

            if (i + 1 != parts.Length)
            {
                current = property.GetValue(current);
            }

            continue;
        }

        field = type.GetField(part, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

        if (field != null)
        {
            property = null;

            if (i + 1 != parts.Length)
            {
                current = field.GetValue(current);
            }

            continue;
        }

        throw new ArgumentException("name");
    }

    if (current == null)
    {
        throw new ArgumentNullException("obj");
    }

    if (property != null)
    {
        property.SetValue(current, value);
    } 
    else if (field != null)
    {
        field.SetValue(current, value);
    }
}

example of use:

public class Panel
{
    public bool Visible { get; set; }
}

public class MyTest
{
    public Panel Panel1 = new Panel();

    public void Do()
    {
        string currPanel = "Panel1";
        currPanel += ".Visible";

        SetValue(this, currPanel, true);
    }
}

and

var mytest = new MyTest();
mytest.Do();

Note that I'm not supporting indexers (like Panel1[5].Something). Supporting int indexers would be feasible (but another 30 lines of code). Supporting not-int indexers (like ["Hello"]) or multi-key indexers (like [1, 2]) would be quite hard.

Upvotes: 2

Related Questions