Home > database >  C# Is there a way to use a variable AS a property?
C# Is there a way to use a variable AS a property?

Time:05-18

I want to use a variable, here i'm using TextName as the variable. then use it AS a property. Of course i cannot because it's a string, but how do i get a variable/string to be treated as the text in the string it's holding? In google sheets this is very similuar to something called an INDIRECT, to be able to be the data you are referring to.

// Code I like to write:
TextName = "richTextBox";
TextName.Text = "text for richTextBox"; 

I want that code to be treated as

richTextBox.Text = "text for richTextBox";

but with richTextBox.Text in full or part to be a variable, so that I can put this entire thing in a method, and only change the variable, and not have an entire method all over the code over and over.

I'm using .NET6.0 if it matters.

CodePudding user response:

I suppose you are going to do this in a Form. In this case, you can add this code into your form:

public string this[string name]
{
    get
    {
        return this.Controls.ContainsKey(name) ?
            this.Controls[name].Text :
            null;
    }
        
    set
    {
        if (this.Controls.ContainsKey(name))
        {
            var control = this.Controls[name];
            control.Text = value;
        }
    }
}

And get/set the text of any Control in this way:

this["richTextBox"] = "text for richTextBox";

var text = this["richTextBox"];

this is your form.

If you are going to use in multiple forms, you can create an extension methods:

public static class FormExtends
{
    public static string GetText(this Form form, string name, string defaultText = null)
    {
        return form.Controls.ContainsKey(name) ?
            form.Controls[name].Text :
            (defaultText ?? string.Empty);
    }

    public static void SetText(this Form form, string name, string text)
    {
        if (form.Controls.ContainsKey(name))
        {
            var control = form.Controls[name];
            control.Text = text;
        }
    }
}

And simplify the code in each form:

public string this[string name]
{
    get { return this.GetText(name); }
    set { this.SetText(name, value); }
}
  • Related