public List<Musteri> musteriListesi;
public void Ekleme()
{
int adet= 0;
Console.WriteLine("Kaç Adet Müşteri Eklenecek?");
adet= Convert.ToInt32(Console.ReadLine());
musteriListesi=Enumerable.Repeat(default(Musteri), adet).ToList();
for (int i = 0; i < adet; i )
{
Console.WriteLine("Müşteri Adı:");
musteriListesi[i].Name=Console.ReadLine(); //==> Error Line
Console.WriteLine("Müşteri Soyadı:");
char ch;
char.TryParse(Console.ReadLine(), out ch);
musteriListesi[i].Gender = ch;
Console.WriteLine("Enter a date: ");
DateTime userDateTime;
if (DateTime.TryParse(Console.ReadLine(), out userDateTime))
{
Console.WriteLine("The day of the week is: " userDateTime.DayOfWeek);
}
else
{
Console.WriteLine("You have entered an incorrect value");
}
musteriListesi[i].BirthDate=userDateTime;
}
}
I created a List from the customer class. I try to add value to the props in the Musteri class into the List I created, but it gives an error. customer =Musteri class
Error Message:
Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object. at ClassMetotDemo.MusteriManager.Ekleme()
CodePudding user response:
This default(Musteri)
evaluates to null, if Musteri
is a reference type, it's default value is null, you'll need to create a new instance of Musteri
when you generate the musteriListesi
list.
Replace your Repeat
logic with:
musteriListesi = Enumerable.Range(0, adet).Select(_ => new Musteri()).ToList();
CodePudding user response:
You are adding null
entries to your list because the default
value of a class is null
, not an empty object of this class. However, using Repeat(new Musteri(), adet)
would not solve the problem, as it would add the same object to all positions of the list, but you must create a new object for every entry.
Use the Add
method to add entries to the list"
musteriListesi = new List<Musteri>(adet);
for (int i = 0; i < adet; i )
{
musteri = new Musteri();
musteriListesi.Add(musteri);
...
musteri.Name = Console.ReadLine();
...
}
Note, using the adet
argument when creating the new list is not strictly necessary as it does not create a list of this size. It only reserves that much space in advance to the list's internal array. This makes adding entries more efficient, as the internal array will not have to be resized. If you don't know the size of the list in advance, you can just write musteriListesi = new List<Musteri>();
.