You can use generics to do this:
public string ConcatValues<T>(params T[] types)
{
// Check to make sure that T is an enumeration.
if (!typeof(T).IsEnum)
{
// Throw an exception.
throw new InvalidOperationException("The type parameter T must be an
enumeration type.");
}
// Create the string builder.
StringBuilder sb = new StringBuilder();
foreach (T type in types)
{
// Append.
sb.Append((int) type);
sb.Append(",");
}
// Remove the comma, if necessary.
if (sb.Length 0)
{
// Remove the comma.
sb.Remove(sb.Length - 1, 1);
}
// Return the string.
return sb.ToString();
}
Note that you have to check to make sure that the type T is an
enumeration at runtime, since the compiler will not allow you to create a
constraint against System.Enum (which all enumerations derive from).
--
- Nicholas Paldino [.NET/C# MVP]
-
mv*@spam.guard.caspershouse.com
<co**********@googlemail.comwrote in message
news:11**********************@22g2000hsm.googlegro ups.com...
Hi
The methods below are identical except they take as arguments
different enum types.
There must be a better way of writing this?
ta
public string ConcatValues(params EnumType1 [] types)
{
StringBuilder sb = new StringBuilder();
bool first = true;
foreach (EnumType1 type in types)
{
if (first)
{
first = false;
}
else
{
sb.Append(",");
}
sb.Append((int)type);
}
return sb.ToString();
}
public string ConcatValues(params EnumType2 [] types)
{
StringBuilder sb = new StringBuilder();
bool first = true;
foreach (EnumType2 type in types)
{
if (first)
{
first = false;
}
else
{
sb.Append(",");
}
sb.Append((int)type);
}
return sb.ToString();
}
etc