I have code that I want to make the following changes:
How do I override ToString()? It says: A static member ...ToString(System.Collections.Generic.List)' cannot be marked as override, virtual, or abstract.
How do I make it generic?
public static override string ToString(this List<int> list) { string output = ""; list.ForEach(item => output += item.ToString() + "," ); return output; }
Thanks!
You cannot use extension methods to override an existing method.
From the spec http://msdn.microsoft.com/en-us/library/bb383977.aspx
"You can use extension methods to extend a class or interface, but not to override them. An extension method with the same name and signature as an interface or class method will never be called. At compile time, extension methods always have lower priority than instance methods defined in the type itself."
If you want to override
ToString()
, you would need to inherit fromList<T>
rather than try to extend it. You have already seen that you cannot mark the static extension method as override, and overload resolution will always go for the member method over an extension method if it is available. Your options areToSpecialString()
MyExtensions.ToString(myList);
You can only override a method if you inherit the base class.
What I would advocate is calling your extension method
.ToCsv()
.What are you trying to achieve? Often I want to output the contents of a list, so I created the following extension method:
It is then consumed like this
EDIT: To make it easier to use for non string lists, here is another variation of above
Now you can consume it like this