-1

I want to display attribute of an object based on the input string . If input is "x" and Object is "obj", i want to display something like "obj.x" without using if,switch or other conditional operators. Can someone help me?

public void My_Method(String input)
{
MyClass  tempVariable=getMyClass();

display something like ---->  tempVariable.input
}

public getMyClass()
{
MyClass value = MyClass();
value.x=10;
value.y=20;
.........
return value;

}


public class MyClass
{
public int x {get;set;}
public int y {get ;set;}
......
}

The purpose of this is as follows Im receiving a dynamic ExpanObject type from a API. There will a lot of name value pairs and one name value pair contains value as comma separated list of some variable names. I have to get the value of these variables

Mridul Raj
  • 1,001
  • 4
  • 19
  • 46
  • 2
    What is actually the problem you are trying to solve? – Steven Sep 17 '12 at 09:48
  • So you mean that the `String` input parameter to your method could be either x, y or z (as strings) based on which you need to access those instance variables of MyClass ? – verisimilitude Sep 17 '12 at 09:52
  • 1
    If so, I don't think so what you are thinking about doing is feasible in `C#`. At the most, you can use `dictionaries`. http://stackoverflow.com/questions/1282888/dynamic-variable-in-c and key in those instance variables. – verisimilitude Sep 17 '12 at 09:56
  • Im receiving a dynamic ExpanObject type from a API. There will a lot of name value pairs and one name value pair contains value as comma separated list of some variable names. I have to get the value of these variables. – Mridul Raj Sep 18 '12 at 04:53

3 Answers3

4

You can use reflection

var fVal = obj.GetType().GetField("x").GetValue(obj);

or

var pVal = obj.GetType().GetProperty("x").GetValue(obj,null);
L.B
  • 114,136
  • 19
  • 178
  • 224
0

Try to use Reflection (less perf ) or Expression Trees (link)

Cybermaxs
  • 24,378
  • 8
  • 83
  • 112
0

I preefer expreesion tree:

 public static class PropertyHelper
    {
        public static string GetName<T>(Expression<Func<T>> e)
        {
            var member = (MemberExpression)e.Body;
            return member.Member.Name;
        }

        public static Type GetPropertyType<T>(Expression<Func<T>> e)
        {
            var member = (MemberExpression)e.Body;
            return member.Type;
        }
    }

And to get names is easy:

MyClass tempVariable = getMyClass();
  string varName = PropertyHelper.GetName(() => tempVariable);
 string propName = PropertyHelper.GetName(() => tempVariable.x);
ígor
  • 1,144
  • 7
  • 16