What I'm doing is looking up a value for a particular field in the hashtable. The object can be a handful of primitive types who's value is destined to be put inside XML but it comes out of the hashtable as an object. So I have the problem of needing to decide what the type is, cast it up and then use that types ToString. It would be nice if I didn't need to cast it but then it will call the ToString on the object type and not the counterpart method on the actual type.
The following code is functionally correct, but I'm not comfortable with it. Perhaps following this comfort path will lead to me being a purist. Either way I would very much appreciate a nicer way to write this if such exists.
public string GetColumnValue(string columnName)
{
object value = item[columnName];
if (value == null)
return string.Empty;
if (value.GetType() == typeof(string))
{
return (string)value;
}
else if (value.GetType() == typeof(double))
{
return ((double)value).ToString();
}
...
}
Type casting is when you assign a value of one primitive data type to another type. In Java, there are two types of casting: Widening Casting (automatically) - converting a smaller type to a larger type size. byte -> short -> char -> int -> long -> float -> double.
Type Casting is a feature in Java using which the form or type of a variable or object is cast into some other kind of Object, and the process of conversion from one type to another is called Type Casting.
lang. Class class is used to cast the specified object to the object of this class. The method returns the object after casting in the form of an object. Return Value: This method returns the specified object after casting in the form of an object.
If all you are doing is calling ToString
, due to the polymorphic nature of C#, the ToString will call the correct implementation, even if all you have is a reference to Object.
E.g.:
var d=DateTime.Now;
object od=d;
Console.WriteLine(od.ToString());
Console.WriteLine(d.ToString()); //same as previous line
Depending on your list of acceptable types, you may want to consider using Convert.ToString and/or the IConvertable interface.
This will allow you to handle most of the primitive types in one shot.
You will still need to handle your null check, however.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With