tags:

views:

50

answers:

2

I'm having the following classes. While trying to set the values of the employee class with the following code, i`m getting the error message:Object reference not set to an instance of an object.

How can I solve it?

public class Employee
{
     public Test[] test{ get; set; }

        public Employee()
        {
           this.test[0].Name = "Tom";
           this.test[0].age= 13;

        }
}



public class Test
{
    public string Name {get; set;}
    public int Age {get; set;}
}
+1  A: 

You should create an instance of array, and array elements before trying to use tham

for example

test = new Test[1]{new Test()};

or

test = new Test[1];
test[0] = new Test();

than you can use tham

this.test[0].Name = "Tom";
this.test[0].age= 13;

If you want the array to actually contain constructed Test elements, then you can use this code:

Test[] arrT = new Test[N];
for (int i = 0; i < N; i++)
{
    arrT[i] = new Test();
}
ArsenMkrt
Thanks for replying. With the following, i`m still having the error message: Object reference not set to an instance of an object. test = new Test [1] { new Test() }; this.test[0].Name = "Tom"; this.test[0].age= 13;
I don't think so, you are doing something wrong in another place. It's working just perfect for me
ArsenMkrt
I have tried both of the answers, but can`t find out why I am getting the error message!
can you provide more code? In which line do you get error?
ArsenMkrt
+1  A: 

You need to create an instance of test variable which is an array of Test[] objects before assigning any values to them. When creating an instance you have to set the number of elements it will hold.

    public class Test
    {
        public string Name { get; set; } public int age { get; set; }
    }

    public class Employee
    {
        public Test[] test { get; set; }

        public Employee()
        {
            test = new Test[1];
            this.test[0] = new Test();
            this.test[0].Name = "Tom";
            this.test[0].age = 13;

        }
    }

If you dont know the number of Test obejct the array will hold, consider using List or ArrayList

Edit. List Example:

    public class Employee
    {
        public List<Test> test { get; set; }

        public Employee()
        {
            this.test.Add(new Test());
            this.test[0].Name = "Tom";
            this.test[0].age = 13;

        }
    }

    public class Test
    {
        public string Name { get; set; } public int age { get; set; }
    }
LnDCobra
I`m still getting the error message at the level of "this.test.Add(new Test());"
whats the error message? By the way, in your original example you named the Test class "test" (lowercase t) when you decalred it, but when you used it in the Employee class you tried to use it with a Capital T ("Test").Ensure the line "public class Test { .... } is correct. I edited my second code so it contains the correct Test class as well
LnDCobra