c# - Initialize an array of a class in a constructor -
i have class garage
has property array of type car
, class in program. i've tried several iterations , run-time errors on of them. nullrefernceexception
whenever try run it. happens in program
class try access length property of carlot
array.
i know has carlot
property of garage
class being array instead of car
. piece missing here array isn't set null when program tries use it?
class program { static void main(string[] args) { garage g = new garage(); //this exception occurs g.carlot[0] = new car(5, "car model"); console.readline(); } } public class garage { public car[] carlot { get; set; } public garage() { } //this should able 0 or greater public garage(params car[] c) { car[] cars = { }; carlot = cars; } } public class car { public int vin { get; set; } public int year { get; set; } public string model { get; set; } public car(int _vin, string _model) { _vin = vin; _model = model; } public car() { } public void print() { console.writeline("here information car {0} , {1} "); } }
instead of using auto property array, can use private variable initialize array when parameterless constructor called in main.
e.g.
private car[] carlot = new car[size]; public car[] carlot { { return carlot; } set { carlot = value; } }
alternatively, in parameterless constructor garage can go ahead , initialize array @ point.
either way, array has instantiated before can assign values it. http://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx
Comments
Post a Comment