Ashkan Mobayen Khiabani Ashkan Mobayen Khiabani - 10 months ago 92
C# Question

Overriding NameValueCollection ToString

I have Written the following extension method to override the


public static string ToString(this NameValueCollection a)
return string.Join("&", a.AllKeys.Select(k => $"{k}={a[k]}"));

But it still uses the default

When I add the
keyword I get an error:

'ToString(NameValueCollection)': no suitable method found to override

And when I add
keyword it says that
keyword is not needed:

'ToString(NameValueCollection)' does not hide an inherited member. The new keyword is not required.

Answer Source

If you want to override ToString() for NameValueCollection, you need to create a new Object which inherits NameValueCollection

public class CustomNameValueCollection:NameValueCollection
     public override String ToString()
         return string.Join("&", AllKeys.Select(k => $"{k}={this[k]}"));

You fill your collection in your new CustomValueCollection and you can call ToString().

CustomValueCollection coll = new CustomValueCollection();
coll.Add("key", "value");

string collString = coll.ToString();