Reputation: 53
I was using the "this" keyword in my default constructor, below is the code in the class movie
namespace Movie_List
{ enum GenreType { Action, War, Drama, Thriller };
class Movie
{
//Data Members
private String _title;
private int _rating;
private GenreType _type;
//Properties
public GenreType GenType
{
get { return _type; }
set { _type = value; }
}
public String Title
{
get { return _title; }
set { _title = value; }
}
public int Rating
{
get { return _rating; }
set { _rating = value; }
}
public Movie()
: this("Jaws", GenreType.Action, 4) { }
public Movie(String title, GenreType type, int rating ) //working ctor
{
Title = title;
GenType = type;
Rating = rating;
}
public override string ToString()
{
return String.Format(" {0} Genre : {1}, Rating: {2:d} Stars. ", Title, GenType, Rating);
}
}
I wanted to read in from a text file so i used this code in the MainWindow.xaml.cs
private void btnLoad_Click(object sender, RoutedEventArgs e)
{
string lineIn = "";
string[] filmarray;
using (StreamReader file = new StreamReader("filmlist.txt"))
{
while ((lineIn = file.ReadLine()) != null)
{
filmarray = lineIn.Split(new char[] { ',' });
moviecollection.Add(new Movie()
{
Title = filmarray[0],
GenType = (GenreType)Enum.Parse(typeof(GenreType), filmarray[1]),
Rating = Convert.ToInt32(filmarray[2]),
});
lstFilms.ItemsSource = moviecollection;
}
}
}
I dont need this bit of code now
: this("Jaws", GenreType.Action, 4)
But when i deleted it, the genre action and rating 0 stars still prints.
Why is this Happening does anyone know?
Upvotes: 0
Views: 76
Reputation: 263723
When you have this initialization:
Movie movie = new Movie();
the empty constructor
public Movie() : this("Jaws", GenreType.Action, 4) { }
calls the overloaded constructor which have several parameters:
public Movie(String title, GenreType type, int rating) { ... }
When you delete this line: this("Jaws", GenreType.Action, 4) { }
, what is happening now is that you are only calling the empty constructor which does nothing at all.
So when you call
int ratingValue = movie.Rating;
the default value of integer which is zero
is returned because you did set anything on it.
UPDATE
a simple if
(maybe, if I understand what you mean)
Assuming Rating
should be greater than zero.
public override string ToString()
{
if (Rating == 0)
{
return String.Format("{0}", Title);
}
else
{
return String.Format(" {0} Genre : {1}, Rating: {2:d} Stars. ", Title, GenType, Rating);
}
}
Upvotes: 1
Reputation: 20606
It's because enum
and int
are always initialized with default value of 0.
It's not like string
- if you don't initialize it will equal null
. If you want to emulate this behavior for int
, you can always try using int?
type.
To get more details on this subject take a look at Default Values Table (C#).
Upvotes: 0