2

so if the string name of a variable is passed into a method, I know which variable to use.

in the following example, the area I need help with is PrintVar(string)...turning the string argument into the variable...so that it prints out "here be variable 1" and "here be variable 2" respectively...Thanks!


class ReflectionTest
{    
    class MyObj
    {
        private string myvar;

        public MyObj(string input)
        {   this.myvar = input; }

        public override string ToString()
        {   return ("here be " + myvar);    }   
    }

    class MyClass
    {
        private MyObj var1;
        private MyObj var2;

        public MyClass()
        {   
            var1 = new MyObj("variable 1");
            var2 = new MyObj("variable 2");
        }

        public void PrintVar(string theVariable)
        { 
            Console.WriteLine(theVariable); 
        }   
    }


    static void Main()
    {
        MyClass test = new MyClass();
        test.PrintVar("var1");
        test.PrintVar("var2");
    }
}
1
  • Most times, it's much easier and better to use collections. Commented Mar 9, 2012 at 7:06

1 Answer 1

6

If you need to fetch things by name, then personally I'd start by using a dictionary in the internal implementation, i.e.

private readonly Dictionary<string,MyObj> fields =new Dictionary<string,MyObj>();

public MyClass()
{
    fields["var1"] = new MyObj("variable 1");
    fields["var2"] = new MyObj("variable 2");
}
public void PrintVar(string fieldName)
{
    Console.WriteLine(fields[fieldName]);
}

The other option would be reflection (GetType().GetFields()):

public void PrintVar(string fieldName)
{
    Console.WriteLine(GetType().GetField(fieldName,
        BindingFlags.NonPublic | BindingFlags.Instance).GetValue(this));
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you! I appreciate the reflection example and your recommended Dictionary implementation ;-)
one additional Question... if I added...public void WriteOut(){ Console.WriteLine("thank you"); }...to the 'MyObj' class...how would I call that within PrintVar(string)? i guess I'm still not sure what reflection returns...
@user1229895 either fields[fieldName].WriteOut(); or ((MyObj)GetType().GetField({same as before}).GetValue(this)).WriteOut();
very much obliged again! you are a sage ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.