MarkP
MarkP

Reputation: 4278

Set value to Object without knowing type

Usually, if the object was a class instance, I'd use reflection to set values to its members. Consider the following:

class Foo
{
  public Control _tCtrl { get; set; }
  public Object _tObj { get; set; }

  public void Set()
  {
    // How do I give tObj the converted value of _tCtrl.ToString() ?

    // var val = Convert.ChangeType( _tCtrl.ToString(), tObj.GetType() );
    // _tObj.SetValue( val );
  }
}

Calling it would be like:

Class Bar
{
  public Int32 _i { get; set; }
}


Bar bar = new Bar();   
Foo foo = new Foo();

foo._tCtrl = new TextBox() { Text = "100" };
foo._tObj = bar._i;    
foo.Set();

Or:

Foo foo = new Foo();
Int32 i;

foo._tCtrl = new TextBox() { Text = "100" };
foo._tObj = i;

foo.Set();    

Anything could be passed into Set(). Assume that I can convert from a String to whatever type is tObj.GetType().

Upvotes: 0

Views: 2030

Answers (2)

Kendall Frey
Kendall Frey

Reputation: 44316

I think what this boils down to is converting a string to any other type. That has problems. How would you convert a string to, say, a Form, a List<>, or a Random? It would require you to write a converter for every type in the .NET Framework (or possibly every existing type in the universe).

You shouldn't be trying to do this. I don't know what you are trying to achieve, but there is almost surely a better way.

Upvotes: 1

Guvante
Guvante

Reputation: 19203

There is no way to allow that kind of syntax, but you can do the following:

foo.Set(bar, "_i");

Where Set uses the following:

type.GetProperty(propertyName, Type.EmptyTypes).SetValue(tObj, value, Type.EmptyTypes);

Where propertyName, tObj, and value are defined elsewhere.

Upvotes: 0

Related Questions