4

I have a C# class that looks like this:

public class Model 
{ 
  public string title;
  public string name;
  ...
}

Somewhere I have a variable with the attribute I need to set "title" for example. My C# is rather rusty but basically what I want to do is:

var attrToBeSet = "title";
var model = new Model();
model[attrToBeSet] = "someValue";

Obviously that is psuedocode but ... Is this even possible with C#?

fubo
  • 44,811
  • 17
  • 103
  • 137
Mike Fielden
  • 10,055
  • 14
  • 59
  • 99

1 Answers1

5

Yes; reflection, in this case of a field (but a property would be better):

var attrToBeSet = "title";
var field = model.GetType().GetField(attrToBeSet);
field.SetValue(model, "someValue");

Note that this is much slower than regular code. If you are doing lots of this, there are ways to make reflection faster via meta-programming, perhaps baking things into an Action<Model,object> or similar via DynamicMethod - but that only matters if doing it lots.

Note that this should really be a property (you should avoid exposing fields directly):

public string Title {get;set;}

then:

var attrToBeSet = "Title";
var prop = model.GetType().GetProperty(attrToBeSet);
prop.SetValue(model, "someValue", null);
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 3
    Holy !@#$% you answer very fast – Only a Curious Mind Aug 08 '14 at 14:40
  • 4
    @LucasAbilidebob sorry, I'll try to be slower in future... ;p (note: I tend to write the *main part* of an answer, and then edit it to improve it a bit... I do not, however, post a 1-line answer just to "reserve a place") – Marc Gravell Aug 08 '14 at 14:40
  • 1
    So fast I cant even accept as the right answer. :) Thanks @MarcGravell – Mike Fielden Aug 08 '14 at 14:42
  • 1
    [This method](http://stackoverflow.com/a/2824409/2441808) (also your answer) is cool too. – Casey Aug 08 '14 at 14:43
  • @emodendroket yeah, that's a more hardcore way of doing it; I would tend to use FastMember or HyperDescriptor (also both mine) before using `Expression`, though – Marc Gravell Aug 08 '14 at 14:50
  • But expressions give you some member of type-safety/Intellisense/etc., so it can be useful, depending on what you're doing. I found that a useful trick anyway. – Casey Aug 08 '14 at 16:53