-3

Let's say I have a C# class like this:

Class Test {
    public string myProp;

    public Test() {
    }
}

//(...)

Test testObject = new Test();

I need to get a reference to that property and set it, in that kind a way:

testObject.GetProperty("myProp") = (...)

I Can't use PropertyInfo.SetValue (and of course in my case I can't do testObject.myProp = (...), I really need to access it that way and be able to set it with the '=' sign. Is it possible?

jean daux
  • 17
  • 3
  • This already has an answer here https://stackoverflow.com/questions/619767/set-object-property-using-reflection – Dan Csharpster Apr 05 '23 at 15:40
  • 2
    `public string myProp;` is *not a property* - it is a field; have you tried `.GetField("myProp").SetValue(...)` ? – Marc Gravell Apr 05 '23 at 15:40
  • 2
    "I Can't use PropertyInfo.SetValue" - why not? It's really unclear where your requirements are coming from. It sounds like you're really going to be fighting C#... – Jon Skeet Apr 05 '23 at 15:44
  • 1
    There is really no way to set property (or filed as shown in the question) by name without using reflection. As @JonSkeet asked it is not clear why you have to avoid SetValue call and hence no way to suggest how to solve *your problem*. As result in general this is duplicate of using reflection - definitely can be re-opened (and possibly answered) if you decide to [edit] the post to clarify you actual goal (i.e. "need to build an expression for LINQ-to-SQL query"). – Alexei Levenkov Apr 05 '23 at 16:46

1 Answers1

0

To be honest, it isn't clear why you can't use reflection here, but: "FastMember" (via nuget) offers an API to do this reasonably efficiently (via some ref-emit at runtime, rather than simply wrapping reflection):

var obj = new Test();
var acc = FastMember.ObjectAccessor.Create(obj);
acc["myProp"] = "boo";
Console.WriteLine(obj.myProp); // "boo" i.e. it worked

but honestly, simple reflection is fine here too:

var obj = new Test();
obj.GetType().GetField("myProp").SetValue(obj, "boo");
Console.WriteLine(obj.myProp); // "boo" i.e. it worked

or even better: think about other ways of achieving this; the number of times you need to access a member by a name not known at compile-time is incredibly rare.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • @MatJ I don't find it entirely impossible that they only know the name; that's ... unusual, but not impossible – Marc Gravell Apr 05 '23 at 15:58
  • Marc BTW can you please take a quick pick at recent `FastMember` PR and related discussion =) – Guru Stron Apr 05 '23 at 16:17
  • Thanks Marc, that's perfect! Concerning the why, it is because I'm not directly dealing with an instance of the class, but with an instance of an interface it implements. – jean daux Apr 06 '23 at 07:51