Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A clean way to cast to an objects actual type

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();
            }
            ...
        }
like image 624
Daniel Revell Avatar asked Feb 16 '10 17:02

Daniel Revell


People also ask

What is type casting in Java?

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.

Which is used for casting of object to a type or a class?

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.

How do you cast an object to a specific class?

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.


2 Answers

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
like image 171
spender Avatar answered Sep 24 '22 00:09

spender


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.

like image 21
Reed Copsey Avatar answered Sep 24 '22 00:09

Reed Copsey