3

I have a collection of classes at my system. So, also i have a simple config file with collection of class names.

And i want to run code like this:

(object as Class).name="some text"; 

Where Class is his class name string from config file. May be i should use a refletion to do this?

Thank you!

Admiral Land
  • 2,304
  • 7
  • 43
  • 81

3 Answers3

6

You can ignore the type and directly use dynamic (that internally uses reflection)...

object obj = ...
dynamic dyn = obj;
dyn.name = "some text";

This works only if name is public. Otherwise you can use reflection...

If name is a property:

Type type = obj.GetType();
PropertyInfo prop = type.GetProperty("name", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
prop.SetValue(obj, "some text");

If it is a field:

Type type = obj.GetType();
FieldInfo field = type.GetField("name", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
field.SetValue(obj, "some text");
xanatos
  • 109,618
  • 12
  • 197
  • 280
1

If the class name is not available at compile time, you have to use reflection or DLR (dynamic) to set the property.

See more in the answer here Set object property using reflection

Community
  • 1
  • 1
Tomas Grosup
  • 6,396
  • 3
  • 30
  • 44
1

It's difficult to tell what your use case is exactly, but here is another angle on your question that may help. I'm assuming that all of the classes you can specify in your config have the same property (i.e. name). If this is the case, you could have all of the classes implement the same interface, then you don't need to worry about the class name. For example:

Your interface:

public interface IName
{
    string Name { get; set; }
}

A class that uses the interface:

public class Something : IName
{
    public string Name { get; set; }
    public string AnotherProperty { get; set; }
}

And a method that uses any object that implements the IName interface:

public void DoSomething(IName input)
{
    Console.WriteLine(input.Name);
}

So now you can call the method without having to worry about class names:

var someObject = new Something();
someObject.Name = "Bob";

DoSomething(someObject);
DavidG
  • 113,891
  • 12
  • 217
  • 223