Generic Conversion Of Types

  • Thread starter Thread starter Jim Heavey
  • Start date Start date
J

Jim Heavey

I am trying to figure out how to write a generic "format" routine to return
a string type variable. I want to pass this routine an object and based on
the type of the object format according to the type. I tried something
like this, but of course it does not like this... How can I accomplish
this?

Here is a snipit of code...

private string ConvertType(object item )
{
string val;
switch (item.GetType())
{
case System.Int32:
val = item.ToString();
break;
case System.Guid:
val = item.ToString();
break;
case System.Single:
FormatTheNumber((single)item)
break;
case System.Double:
FormatTheNumber((Double)item)
break;
}
}

Thanks in advance for your assistance!!!
 
Hi,

The switch statement will not work in this case, if I am not mistaken
you will get a compile error along the lines of the switch expression
not being an integral type.

You could use the 'is' operator as follows

if ( item is System.Int32 )
...
else if ( item is System.Single )
...
else it ( item is System.Double )
...

Hope this helps

Chris Taylor
http://www.xanga.com/home.aspx?user=taylorza
 
Jim Heavey said:
I am trying to figure out how to write a generic "format" routine to return
a string type variable. I want to pass this routine an object and based on
the type of the object format according to the type. I tried something
like this, but of course it does not like this... How can I accomplish
this?

Here is a snipit of code...

private string ConvertType(object item )
{
string val;
switch (item.GetType())
{
case System.Int32:
val = item.ToString();
break;
case System.Guid:
val = item.ToString();
break;
case System.Single:
FormatTheNumber((single)item)
break;
case System.Double:
FormatTheNumber((Double)item)
break;
}
}

Thanks in advance for your assistance!!!


To get the switch to work, add a "ToString()" to the "item.GetType()"
so you get " switch (item.GetType().ToString()) ".
Also change the case-arguments to strings: case "System.Int32" and so on.

You could build cases for the types that require special formatting (like
your
System.Single) and handle all simple ToString() cases in a "default".


Hans Kesting
 
Hi Jim,

I was just reading an article on c# generics (msdn - csharp
homepage)... It might be something worth looking into for a future
version of this routine.. But in the interim try this.

private string ConvertType(object item )
{
Type t = item.GetType();
string val = t.ToString();
string retval="";

switch (val)
{
case "System.Double":
retval = item.ToString("d");
break;
default:
//handle all cases except
really unusual types
retval = (string) item.ToString("r");
break;

}
return retval;
}
 
Back
Top