Override .ToString method c#
Solution 1:
You are returning a string that just says the phrase _name + _number + _date + _salary
.
What you likely wanted to do is build a string using those fields. If you wanted them all mushed together Concat would work, but it would be highly un-readable
public override string ToString()
{
return String.Concat(_name, _number, _date, _salary);
}
However what would be better is to use Format and include labels with the values
public override string ToString()
{
return String.Format("Name:{0}, Number:{1}, Date:{2}, Salary:{3}",_name, _number, _date, _salary);
}
If you are using C# 6 or newer you can use the following cleaner format
public override string ToString()
{
return $"Name:{_name}, Number:{_number}, Date:{_date}, Salary:{_salary}";
}
Which is the exact same logic as the previous String.Format
version.
Solution 2:
The reason people override the ToString()
method is to have a default string representation of your object, usually for display to the user or in a log or console, like this:
Console.WriteLine(yourClassObject);
If you do not override the ToString()
, then its default implementation is to return the fully qualified name of your object, like this:
YourNamespace.YourClassName
By changing the inherited implementation (from System.Object
), then you can make a nicer (read: prettier) representation, like this:
public override string ToString()
{
return String.Format("This instance of my object has the following: Name = {0}, Number = {1}, Date = {2}, Salary = ${3}", _name, _number, _date, _salary);
}
Solution 3:
Rather try something like
public override string ToString()
{
return String.Format("Name : {0}, number {1}, date {2}, salary {3}",_name,_number,_date,_salary);
}
But it neads to be part of the class
so
class Employee
{
private string _name;
private string _number;
private int _date;
private int _salary;
.....
public override string ToString()
{
return String.Format("Name : {0}, number {1}, date {2}, salary {3}",_name,_number,_date,_salary);
}
}
Have a look at String.Format Method
Replaces each format item in a specified string with the text equivalent of a corresponding object's value.
Solution 4:
If you are using C# 6 (or later) use the nameof()
method for the property names in the string in case the property names change. You can also use the $""
notation instead of using string.Format()
.
For example:
public override string ToString()
{
return $"{nameof(Name)}: {_name}";
}