Gopi Kishan Mariyala put you on the right track here: the essential problem here is that the Cars collection is not initialized.
You can save some typing like this:
public class Car
{
public string Brand { get; set; }
public string GearBox { get; set; }
public string Paint { get; set; }
public int Wheels { get; set; }
public Car(string brand, string gearbox, string paint, int wheels)
{
Brand = brand;
GearBox = gearbox;
Paint = paint;
Wheels = wheels;
}
}
public class CarItemSource
{
public List<Car> cars { get; set; }
public CarItemSource()
{
cars = new List<Car>
{
new Car ("Audi","Automatic","Yello", 4 ),
new Car ("Maruti 800", "Manual", "White", 4 ),
new Car ("Vaux", "Manual", "Dark Black", 4 ),
new Car ("TATA", "Manual", "Lime Green", 4 )
};
}
}
It is tedious to pass in a bunch of parameters and have to assign them to the Class' variables: but, a good reason to get in the habit of doing this is that the next version of C#
may automatically generate the Property variable back-stores for you: [
^].
However, note that in the above, and in all the responses to this thread, that you could create any number of new instances of the CarItemSource Class, and each one will
repeat having the identical internal List<Car>. imho, that is not a good thing.
So, I suggest you reconsider your design here, with the goal of creating only one unique List<Car>.
You might think you could solve this using this type of Class definition:
public class CarItemSource: List<Car>
{
public CarItemSource()
{
if(this.Count == 0)
{
this.AddRange( new List<Car>
{
new Car ("Audi","Automatic","Yello", 4 ),
new Car ("Maruti 800", "Manual", "White", 4 ),
new Car ("Vaux", "Manual", "Dark Black", 4 ),
new Car ("TATA", "Manual", "Lime Green", 4 )
});
}
}
}
But, that has the same problem: you can create multiple instances of CarItemSource, and the List<Car> is re-created (I have had more than one student who thought they solved this type of problem with this type of clever strategy !).
The obvious alternative is making CarItemSource a static Class:
public static public class CarItemSource
{
public static List<Car> CarList = new List<Car>
{
new Car ("Audi","Automatic","Yello", 4 ),
new Car ("Maruti 800", "Manual", "White", 4 ),
new Car ("Vaux", "Manual", "Dark Black", 4 ),
new Car ("TATA", "Manual", "Lime Green", 4 )
};
}
Test, somewhere in a method, like this:
Car aCar = CarItemSource.CarList[0];
string carName = aCar.Brand;
Classes that have one-and-only-one possible instance are, technically, referred to as "Singletons." For an in-depth consideration of Singletons in C#, Jon Skeet, as usual, has the definitive analysis: [
^].