1

I have a class called Receive and it has a variable public int head=10 for example.

In a different class called Mover I will set a new variable private Receive bodypart.

What I want is to take the value of head of bodypart without using the command bodypart.head but with a string, for example:

string bodyname = "head";

int v = bodypart.bodyname; 

I know that this doesn't work and why but I can't find another method. I already look for reflection but didn't get it and don't know if it's the best for this.

2 Answers 2

1

It looks like you can use Dictionary collection here. For example:

// Receieve class inherits Dictionary. Use <string, object> if your values  
// are of different types
class Receive : Dictionary<string, int> {}

class Mover
{
   private Receive bodypart;

   // assigns value to bodypart field
   public Mover(Receive bodypart)
   {
       this.bodypart = bodypart;
   }

   // get element from bodypart using string argument
   public int GetBodyPart(string name)
   {
       return bodypart[name];
   }
}

class Class26
{
    static void Main()
    {
        // instantiates collection
        Receive res = new Receive();

        // add elements to collection
        res.Add("head", 5);

        // instantiates Mover and pass collection as parameter to ctor
        Mover m = new Mover(res);

        // takes one element from collection
        int a = m.GetBodyPart("head");

        Console.WriteLine(a);
    }
}

Output : 5

Sign up to request clarification or add additional context in comments.

Comments

1

Reflection will do the task in a way like that

  using System.Reflection;
  ...

  public class Receive {
    // using public fields is a bad practice
    // let "Head" be a property 
    public int Head {
      get;
      set;
    }

    // Bad practice
    public int UglyHead = 5;

    public Receive() {
      Head = 10;
    }
  }

  ...

  string bodyname = "Head";

  Receive bodyPart = new Receive();
  // Property reading 
  int v = (int) (bodyPart.GetType().GetProperty(bodyname).GetValue(bodyPart));
  // Field reading
  int v2 = (int) (bodyPart.GetType().GetField("UglyHead").GetValue(bodyPart));

2 Comments

Hmm what I really would like was public fields but either way (public or property) I am getting this type of error - "A field initializer cannot reference the nonstatic field, method, or property `Mover.bodypart' " what may be the cause?
@Fatias7: seems that you assignes a field by value from other field/property etc. e.g. private int SomeField = SomeOtherField; msdn.microsoft.com/en-us/library/5724t6za(v=vs.90).aspx

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.