1

I have a method that can be called via obj.description

public class FromJS
{
    public String description { get; set; }
}

FromJS obj = new FromJS();
obj.description;

is it possible to call it like this

String val = "description";

obj.val
Igor Ralic
  • 14,975
  • 4
  • 43
  • 51
momokjaaaaa
  • 1,293
  • 3
  • 17
  • 32
  • You're looking for reflection. However, that is usually a bad idea. – SLaks Feb 23 '14 at 17:02
  • how to do that on reflection? and why is it a bad idea? – momokjaaaaa Feb 23 '14 at 17:03
  • 1
    possible duplicate of [Get property value from string using reflection in C#](http://stackoverflow.com/questions/1196991/get-property-value-from-string-using-reflection-in-c-sharp) – ProgramFOX Feb 23 '14 at 17:04
  • @ProgramFOX but I dont understand that. – momokjaaaaa Feb 23 '14 at 17:05
  • @momokjaaaaa So read about the reflection something on the internet and then come back. You can't really skip studying if you want to use knowledge. – Ondrej Janacek Feb 23 '14 at 17:06
  • 1
    If you use the `GetPropValue` method of that question, just use this code: `string descr = (string)GetPropValue(obj, "description");` – ProgramFOX Feb 23 '14 at 17:06
  • @OndrejJanacek let's just say I am a slow learner who had done my homework but still couldnt get it right therefore I jumped into stackoverflow looking for help. – momokjaaaaa Feb 23 '14 at 17:09
  • This question appears to be off-topic because it is way too broad, and the person asking could have done the research suggested to him in the comments – Noctis Apr 28 '14 at 20:54
  • possible duplicate of [Calling a function from a string in C#](http://stackoverflow.com/questions/540066/calling-a-function-from-a-string-in-c-sharp) – H H May 31 '14 at 12:49

1 Answers1

2

I see the question is coming from a user having experience in scripting languages (that have late-binding for methods, properties by default). Those languages usually support easy syntax for "evaluating" a string as a piece of program.

C# is a stongly typed language and it supports late-binding as an exception, so there is no straight-forward solution as an eval() in php, perl, python or ruby. When working with C#, please either try to find a solution where you do not need such tricks, or use reflection as some comments suggested.

A beginner's intro for reflection in .NET: http://csharp.net-tutorials.com/reflection/introduction/

wigy
  • 2,174
  • 19
  • 32