tags:

views:

80

answers:

3
public List<string> Attributes = new List<string>();

public void Add(string key, string value)
{
    if (value.ToString() != "")
    {
        Attributes.Add(key + "=\"" + value + "\" ");
    }
}

public void Add(string key, int value)
{
    if (value.ToString() != "")
    {
        Attributes.Add(key + "=\"" + value + "\" ");
    }
}

So, instead of having two Add functions, could we make just one? For example

public void Add(string key, <var> value)
{
    if (value.ToString() != "")
    {
        Attributes.Add(key + "=\"" + value + "\" ");
    }
}
+5  A: 

Note that in this case, the integer version of your function has to be converted to a string anyway for inclusion in the list. So if your entire problem is really as stated, you only need the string version of your function and can just call it like this:

int SomeValue = 42;
string SomeName= "The Answer to Life, the Universe, and Everything";
Add(SomeName, SomeValue.ToString());

But if you are asking about a more general problem, you can just use the object type, like this:

public void Add(string key, object value)
{
    string valueString = value.ToString();
    if (!string.IsNullOrEmpty(valueString))
    {
        Attributes.Add(key + "=\"" + valueString + "\" ");
    }
}

Note that this version has to create an extra variable and call your argument's .ToString() method, neither of which are needed for the string-only version of the function. This extra work is minuscule, and will hardly drive performance for your app; but it's not free either. However, the nice thing here is that if you call it with a string argument overload-resolution should call the (better) string-version of the function. So you would still want to define two methods, but as you discover more types you need to worry about you don't have to keep adding methods. It stops at two.

Joel Coehoorn
+1  A: 

use Object for the type.

public void Add(string key, object value)
{
     if(value == null) {return;}

     var sval = value.ToString();
     if(sval != "")
     { Attributes.Add( key + "=\"" + sval + "\""}
}
dan
+4  A: 
public void Add<T>(string key, T value)
{
    if (value.ToString() != "")
    {
        Attributes.Add(key + "=\"" + value + "\" ");
    }
}

usage

Add("key", 22);
Add("key", "value");
Matt Briggs
Much, much better than type-unsafe methods.ps. The Add's can be used without type following them, as the type is inferred by the compiler from the value being passed in. eg. Add("key", 1) and Add("key", "value")
Will
There's no reason for a generic in this case. If you don't like object, pretend it's some magic "IStringable" interface instead.
Joel Coehoorn