C# Array Property

lankapala
lankapala used Ask the Experts™
on
Hi,
I have a created class  and this class i created property  
see my code
public class Test
{

public Test2[] runCode
{

get;
set;
}

}

public class Test2
{
public string name
{
get;
set;
}


}

Open in new window


I need to know how to call this class and assigned to another class
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Try something like:
    class Employee
    {
        public string Name
        {
            get;
            set;
        }

        public int Id
        {
            get;
            set;
        }
    }

    class Department
    {
        public Employee[] Employees
        {
            get;
            set;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var d = new Department();
            d.Employees = new Employee[3];
            d.Employees[0] = new Employee() { Name = "John", Id = 1001 };
            d.Employees[1] = new Employee() { Name = "Bob", Id = 1002 };
            d.Employees[2] = new Employee() { Name = "Mary", Id = 1003 };
        }
    }

Open in new window

Author

Commented:
@Flabio Gates

I already check that example
I already check that example
What does this mean? Did it not work? What exactly did you do? Show your code!
What you need to do first before assigning values to your array, is initialize your array.
I've shown you how to do that in line 30 of my example above.
Have you initialized your array?
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
You should really be using a Collection and not an Array for public properties, and that collection should be Immutable (you can Add/Remove from the List, but you can't Set the list to something else!)

using System.Collections.ObjectModel;

public class Test
{
	public Test()
	{
		RunCode = new Collection<Test2>();
	}
	
	public Collection<Test2> RunCode
	{
		get;
	}

}

public class Test2
{
	public string Name
	{
		get;
		set;
	}
}

Open in new window

Now you can instantiate a new Test() and simply add new Test2() items to the RunCode collection:

var myTest = new Test();

myTest.RunCode.Add( new Test2 { Name = "Chris" } );
myTest.RunCode.Add( new Test2 { Name = "lankapala" } );

var another = new Test2();
another.Name = "Some Name";
myTest.RunCode.Add( another );

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial