Override .ToString method c#
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.
How can I override ToString() method for all IEnumerableInt32?
How can I achieve this so that my ToString() implementation is called when I call .ToString() on List for example?
You can't, basically. Extension methods are only used if no matching instance method can be found.
I suggest you give your method a different name, avoiding the problem - and the potential confusion your method would cause.
Note that even if extension methods were matched in preference to (say) methods declared on object
, it would only make a difference for your own code being compiled with an appropriate using
directive - not any other code which has already bound the call to the normal one.
If you can give more information about what you're trying to achieve, we may be able to help you more - but for the moment, something like ToDelimitedString
(or whatever your method does) sounds like the best bet to me.
override ToString() with override and new keyword
It makes a difference when you do this:
object a = new A(); // notice the type of the variable here!
object b = new B();
Console.WriteLine(a.ToString());
Console.WriteLine(b.ToString());
a.ToString()
will not call your implementation of ToString
and will instead call object.ToString
, which returns the fully qualified type name of the object. b.ToString()
will call your implementation.
What you did in B
is called overriding. What you did in A
is called hiding. Hiding loses its effect when the compile time type of a variable is not that type anymore. Your implementation of ToString
will only be called when the compile time type is A
.
Learn more here.
How can I override the ToString() method in C#?
As per your question, to change some characters in the ToString
implementation, you need to call the existing ToString
method by using the base
keyword:
public override string ToString()
{
return base.ToString().Replace("something", "another thing");
}
Note that if you forget the base
keyword it will call itself repeatedly until you get a StackOverflowException
.
2 override ToString() methods across multiple classes
It's returning Item.ToString()
because you're calling it when you do stuff += items.ToString();
.
Instead, just do:
string stuff = "Items: ";
for (int i = 0; i < list.Count; i++)
{
Item items = list[i];
stuff += items.Name + ", ";
}
// Remove the last comma
stuff = stuff.Substring(0, s.LastIndexOf(", "));
return name + stuff;
If we don't remove the last comma, we get this:
"Items: Ipod, Motorolla, Samsung, Nokia, "
Instead of:
"Items: Ipod, Motorolla, Samsung, Nokia"
Related Topics
C# Httpwebrequest Command to Get Directory Listing
Passing an Empty Array as Default Value of an Optional Parameter
How to Override a Non-Virtual Method
Use the Long Reserved Word as a Variable Name in C#
System.Text.JSON: How to Specify a Custom Name for an Enum Value
Drag and Drop to Desktop/Explorer
How to Add a .Dll Reference to a Project in Visual Studio
How to Use the Iequalitycomparer
How to Check If File Exists on Ftp Before Ftpwebrequest
Simple Injector Unable to Inject Dependencies in Web API Controllers
5.7.57 Smtp - Client Was Not Authenticated to Send Anonymous Mail During Mail from Error
How to Keep the Delimiters of Regex.Split
Url Mapping with C# Httplistener
Sending Email with Attachments from C#, Attachments Arrive as Part 1.2 in Thunderbird
Anonymous Method in Invoke Call
Getting HTML Body Content in Winforms Webbrowser After Body Onload Event Executes