tags:

views:

148

answers:

2

Hi all, I need to determine whether the ToString() method of an object will return a meaningful string instead of its class name. For example, bool, int, float, Enum, etc. returns meaningful string, instead an instance of ArrayList will return "System.Collections.ArrayList". If there a simple way to archive that?

Thanks in advance.

Regards, Wayne

+21  A: 

You could compare object.ToString() with object.GetType().ToString() ?

Kindness,

Dan

Daniel Elliott
Heh, +1. Actually that's the most straightforward solution :-)
Joey
Well, object.GetType().ToString() ;-)
Wim Hollebrandse
Great suggestion (+1). Only it should be to compare `object.ToString()` with `object.GetType().ToString()` .
awe
That's the simplest and good enough solution I think. thanks Dan.
Wen Q.
Crikey, ramping up the rep Dan on this trivial one. ;-) Nice!
Wim Hollebrandse
+3  A: 

You can use reflection to check if class of object overrides toString. Like this

if (obj.GetType().GetMethod("toString",
    BindingFlags.Instance |
    BindingFlags.Public |
    BindingFlags.DeclaredOnly) != null)
{
    // do smth
}

Update - see if any base class has toString implementation that is not from Object.

        MethodInfo pi = null;
        Type t = obj.GetType(0;
        while (t != typeof(object) && pi == null)
        {
            pi = t.GetMethod("toString",
                BindingFlags.Instance |
                BindingFlags.Public | 
                BindingFlags.DeclaredOnly);
            t = t.BaseType;
        }

        if (pi != null)
        {
            // do smth
        }
Dmitry
If the tested object inherits from a type which does override ToString() you would get incorrect results. To prevent this you would have to recursively step through the supertypes as well until you are arrived at Object.
frenetisch applaudierend
Is it possible to do something like `if (obj.GetType().GetMethod("toString") == typeof(Object).GetMethod("toString") ) { ... }` ?
awe
The problem is that Object does not have "Meaningful" implementation of toString, and some other standart base classes, such as Component, also has toString implementation which is not meaningful.
Dmitry
I think the your ideas is similiar to Dan's. Thought I could only pick one as the answer.Thanks.
Wen Q.