Create a function that takes a Property and a Value as a parameter

This might be a little out there, but lets say that I really want to pass a property of a complex class to a function that will assign the property a value.

Example:

Private Void AssignValueToProperty(Property property, Object Value)
{
property = Value
}

Form1_Load()
{
AssignValueToProperty(This.BackColor, Color.Red)
AssignValueToProperty(This.Text, "Form1")
AssignValueToProperty(This.Size, new Size(500,500))
}

Is such a function possible, maybe using tools like reflection can someone post a quick example of how I would do this


Answer this question

Create a function that takes a Property and a Value as a parameter

  • ritzratz

    Badass, Thanks

  • A1Programmer

    not quite sure what you mean. you can use the public properties approach. Example:

     

    //top of class, global variable declaration:

    private string theName = String.Empty;

     

    public string TheName

    {

       get { return this.theName; }

       set { this.theName = value; }

    }

     

    then access it from another class or the same class:

     

    this.TheName = "test123";

    MessageBox.Show(this.TheName);

     

    would show "test123"



  • Dhaval-Patel

    Hi,

    yes, you could do this with the help of Reflection:

    private void AssignValueToProperty(object myObject, string propertyName, object propertyValue)
    {
    Type type = myObject.GetType();
    PropertyInfo propertyInfo = type.GetProperty(propertyName);
    propertyInfo.SetValue(myObject, propertyValue,
    null);
    }

    AssignValueToProperty(textBox1, "Text", "This is a new text");

    Andrej



  • Create a function that takes a Property and a Value as a parameter