create list of objects without using list method or library. c#
My situation
- create a list of objects using just classes
This how code work
- with the class
ListRatings
i can create a list ofRating
(without using list method that c# offer with the library System.Collections.Generic)
(you can see what attribute and method have class ListRatings
and class Rating
in code bellow)
Issue
when i try to print all rating i added to my list, my program print just first and last!
My code
class ListRating:
public class ListRatings
{
private Rating first;
private Rating last;
public ListRatings()
{
first = null;
last = null;
}
public void InsertNewRat(Rating rating)
{
if (first == null)
{
first = rating;
last = rating;
}
else
{
first.setNext(rating);
last.setNext(rating);
}
}
public void PrintRats()
{
Rating e = first;
Console.WriteLine(e.getMatter());
Console.WriteLine(e.getDate());
Console.WriteLine(e.getRate());
e = e.getNext();
Console.WriteLine(e.getMatter());
Console.WriteLine(e.getDate());
Console.WriteLine(e.getRate());
e = e.getNext();
Console.WriteLine(e.getMatter());
Console.WriteLine(e.getDate());
Console.WriteLine(e.getRate());
}
}
class Rating:
public class Rating
{
private int rate;
private string matter;
private DateTime date;
private Rating next;
public Rating(int rate, string matter, DateTime date)
{
this.rate = rate;
this.matter = matter;
this.date = date;
next = null;
}
public int getRate()
{
return rate;
}
public string getMatter()
{
return matter;
}
public DateTime getDate()
{
return date;
}
public Rating getNext()
{
return next;
}
public void setNext(Rating valutazione)
{
next = valutazione;
}
}
Main:
static void Main(string[] args)
{
ListRatings lr = new ListRatings();
Rating r1 = new Rating(9, "Math", new DateTime(2021, 10, 5));
Rating r2 = new Rating(10, "sport", new DateTime(2021, 11, 3));
Rating r3 = new Rating(6, "English", new DateTime(2021, 11, 7));
lr.InsertNewRat(r1);
lr.InsertNewRat(r2);
lr.InsertNewRat(r3);
lr.PrintRats();
Console.ReadKey();
}
OUTPUT
Math
05/10/2021 00:00:00
9
English
07/11/2021 00:00:00
6
and the program stop and say error: System.NullReferenceException [is in the second e.getNext();
i used in the class ListRating
]
with this output you can see that is printing the first one and jump to the last one without printing the second one.
The output i need is
Math
05/10/2021 00:00:00
9
Sport
10
03/11/07 00:00:00
English
07/11/2021 00:00:00
6
sorry for my bad english
Solution 1:
You aren't correctly updating your linked list. This code:
else
{
first.setNext(rating);
last.setNext(rating);
}
always sets both the first and last node's next node to the one you're trying to insert.
Instead, you want
else
{
last.setNext(rating);
last = rating;
}
This sets the node that's currently last to the new node, then updates your pointer to the last node to rating, which should now be last in the linked list.
As for the NullReferenceException, @TheVillageIdiot is correct