Search code examples
c#overridingnamevaluecollection

Overriding NameValueCollection ToString


I have Written the following extension method to override the NameValueCollection.ToString:

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

But it still uses the default ToString method.

When I add the override keyword I get an error:

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

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

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


Solution

  • 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();