How to override ToString () and implement a generic?

I have a code that I want to make the following changes:

  • How to override ToString ()? It says: static member ... ToString (System.Collections.Generic.List) 'cannot be marked as overriding, virtual or abstract.

  • How to make it common?

    public static override string ToString(this List<int> list) { string output = ""; list.ForEach(item => output += item.ToString() + "," ); return output; } 

Thanks!

0
source share
4 answers

What are you trying to achieve? Often I want to display the contents of a list, so I created the following extension method:

 public static string Join(this IEnumerable<string> strings, string seperator) { return string.Join(seperator, strings.ToArray()); } 

Then it is consumed as follows

 var output = list.Select(a.ToString()).Join(","); 

EDIT . To make it easier to use for lists without strings, here is another option above

 public static String Join<T>(this IEnumerable<T> enumerable, string seperator) { var nullRepresentation = ""; var enumerableAsStrings = enumerable.Select(a => a == null ? nullRepresentation : a.ToString()).ToArray(); return string.Join(seperator, enumerableAsStrings); } public static String Join<T>(this IEnumerable<T> enumerable) { return enumerable.Join(","); } 

Now you can use it like this

 int[] list = {1,2,3,4}; Console.WriteLine(list.Join()); // 1,2,3,4 Console.WriteLine(list.Join(", ")); // 1, 2, 3, 4 Console.WriteLine(list.Select(a=>a+".0").Join()); // 1.0, 2.0, 3.0, 4.0 
+3
source

If you want to override ToString() , you need to inherit from List<T> , and not try to extend it. You have already seen that you cannot set the static extension method as an override, and overload resolution will always be used for the member method by the extension method, if available. Your options

  • Inheritance and redefinition
  • Change the name of the extension method to something else. ToSpecialString()
  • Call the method directly using the class name MyExtensions.ToString(myList);
+4
source

You cannot use extension methods to override an existing method.

From the specification 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 the interface or class method will never be called. At compilation, extension methods always have lower priority, than the instance methods defined in the type itself. "

+3
source

You can override a method only if you inherit a base class.

What I would defend calls the .ToCsv() extension method.

+1
source

Source: https://habr.com/ru/post/1401315/


All Articles