0

I would like to understand how to initialize array object from an outside class. Please refer to the code below:

Class C
{
    private string name { get; set; }
    private string value { get; set; }
}

Class B
{
    private C[] field;
    public C[] Field { get; set; };
}

Class Program 
{
    public static void Main(string[] args)
    {
        B b = new B();
        /* my question was how to initialize this array object inside B class */
        b.Field = new C[1]; 
        b.Field[0] = new C(); 
        /* Now I can access b.Field[0].name */ 
    }
}

Note that I cannot change Classes B and C as they are already provided to me. Thanks for your help.

10
  • Is there no constructor of C you can use? Commented Oct 21, 2013 at 4:19
  • If you can't change the public interface for C perhaps this will help: stackoverflow.com/questions/934930/… Commented Oct 21, 2013 at 4:23
  • Unfortunately, I cannot modify class C or class B. :( Commented Oct 21, 2013 at 4:24
  • You should be wary of abusing reflection for purposes like this, but sometimes it may be a necessary evil. Commented Oct 21, 2013 at 4:24
  • You can't set the name and value of C because they are private (short of reflection) - the array is irrelevant. Commented Oct 21, 2013 at 6:48

1 Answer 1

2

First of all, you can not modify name and value properties from outside of C because they are private.
After making your name and value properties public, you can instantiate your array as follows.

B b = new B();
b.Field = new C[] {new C {name = "lorem", value = "ipsum"}, new C {name = "dolor", value = "sit"}};

If you use Reflection, create your C objects through a factory as follows.

public class CFactory
{
    public C Create(string name, string value)
    {
        C result = new C();
        var props = result.GetType().GetProperties(BindingFlags.NonPublic | BindingFlags.Public
                                                | BindingFlags.Instance | BindingFlags.Static);

        var nameProp = props.FirstOrDefault(p => p.Name == "name");
        var valProp = props.FirstOrDefault(p => p.Name == "value");

        if (nameProp != null) nameProp.SetValue(result, name);
        if (valProp != null) valProp.SetValue(result, value);

        return result;
    }
}

and use it;

B b = new B();
var fac = new CFactory();
b.Field = new C[] {fac.Create("lorem", "ipsum"), fac.Create("dolor", "sit")};
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.