momokjaaaaa
momokjaaaaa

Reputation: 1303

C# call a method using string

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

Upvotes: 1

Views: 115

Answers (1)

wigy
wigy

Reputation: 2222

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/

Upvotes: 2

Related Questions