Thursday, March 20, 2014

Initialize class as array and assign values to its elements using C#


Suppose you have ClassA with three members. When you try to initialize class as  
ClassA[] varrayData = new ClassA[Length];
at this point your class initializes not class members.When you try to access the class members it throws null exception.    So solve the issue, find the simple way of initialize class as array with its members
 public class ClassA
    {
        public string Name { get; set; }
        public double Address { get; set; }
        public string Notes { get; set; }
    }

    public void YourMethod()
    {
        ClassA[] varrayData = InitializeArray<ClassA>(Length);
        for (var j = 0; j < Length; j++)
        {
            varrayData[j].Name = "testname" + j;
            varrayData[j].Address = ""
            testAddress + j;
            varrayData[j].Notes = "testNotes" + j;
        }
    } 
    //use this piece of code that does the magic:
    private T[] InitializeArray<T>(int length) where T : new()
    {
        T[] array = new T[length];
        for (int i = 0; i < length; ++i)
        {
            array[i] = new T();
        }
        return array;
    }

No comments:

Post a Comment