E
Ethan Strauss
Hi,
I have written a generic method which does different things depending on
the type of the parameter. I got it to work, but it seems really inelegant.
Is there a better way to do this?
In the code below, ColumnMap is a simple struct which basically has three
properties, Header (a string), Index (an int), TypeOfData (which is a
DataType which is a local eNum). _Mapping is a local List<ColumnMap>.
public ColumnMap GetMap<T>(T value)
{
Type ThisType = typeof(T);
foreach (ColumnMap ThisMap in _Mapping)
{
if (ThisType == typeof(string))
{
if (ThisMap.Header.ToUpper() ==
value.ToString().ToUpper())
{
return ThisMap;
}
}
if (ThisType == typeof(int))
{
if (ThisMap.Index == int.Parse(value.ToString()))
{
return ThisMap;
}
}
if (ThisType == typeof(DataType))
{
if (ThisMap.TypeOfData.ToString() == value.ToString())
{
return ThisMap;
}
}
}
return new ColumnMap();
}
}
I would have prefered to do my comparisons by casting value to string, int,
ot DataType, but that gave me "cannot convert Type 'T' to ____" errors when
compiling.
I know could have written this as three overloaded methods with different
signatures, but I thought using a single Generic method would be easier.
Thanks for any thoughts!
Ethan
Ethan Strauss Ph.D.
Bioinformatics Scientist
Promega Corporation
2800 Woods Hollow Rd.
Madison, WI 53711
608-274-4330
800-356-9526
(e-mail address removed)
I have written a generic method which does different things depending on
the type of the parameter. I got it to work, but it seems really inelegant.
Is there a better way to do this?
In the code below, ColumnMap is a simple struct which basically has three
properties, Header (a string), Index (an int), TypeOfData (which is a
DataType which is a local eNum). _Mapping is a local List<ColumnMap>.
public ColumnMap GetMap<T>(T value)
{
Type ThisType = typeof(T);
foreach (ColumnMap ThisMap in _Mapping)
{
if (ThisType == typeof(string))
{
if (ThisMap.Header.ToUpper() ==
value.ToString().ToUpper())
{
return ThisMap;
}
}
if (ThisType == typeof(int))
{
if (ThisMap.Index == int.Parse(value.ToString()))
{
return ThisMap;
}
}
if (ThisType == typeof(DataType))
{
if (ThisMap.TypeOfData.ToString() == value.ToString())
{
return ThisMap;
}
}
}
return new ColumnMap();
}
}
I would have prefered to do my comparisons by casting value to string, int,
ot DataType, but that gave me "cannot convert Type 'T' to ____" errors when
compiling.
I know could have written this as three overloaded methods with different
signatures, but I thought using a single Generic method would be easier.
Thanks for any thoughts!
Ethan
Ethan Strauss Ph.D.
Bioinformatics Scientist
Promega Corporation
2800 Woods Hollow Rd.
Madison, WI 53711
608-274-4330
800-356-9526
(e-mail address removed)