user759913
user759913

Reputation: 41

Initialize array object inside a different class C#

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.

Upvotes: 0

Views: 2687

Answers (1)

mehmet mecek
mehmet mecek

Reputation: 2685

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")};

Upvotes: 2

Related Questions