Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to tell if an object has implemented ToString explicitly in c#

I am trying to log information about the state of some objects and classes in my code. Not all the classes or libraries were implemented with Serialization. So I am using Reflection on the Properties to write out an XML document of the state. However, I have a challenge in that some objects like builtin Classes (ie Strings, DateTime, Numbers etc...) have a ToString function that prints out the value of the class in a meaningful way. But for other classes, calling ToString just uses the inherited base ToString to spit out the name of the object type (For example a Dictionary). In that case I want to recursively examine to properties inside that class.

So if anyone can help me with reflection to either figure out if there is a ToString implemented on the property I'm looking at that isn't the base method OR to point out the proper way of using GetValue to retrieve collection properties I would appreciate it.

J

like image 346
Jason Avatar asked Sep 21 '11 22:09

Jason


People also ask

Does every object have a toString method?

Every object type has a method called toString that returns a string representation of the object. When you display an object using print or println , Java invokes the object's toString method.

Is toString inherited from object?

The toString method is a method of the object class in java and it is inherited by all the classes in java by default. It provides the string representation of any object in java.

Is toString method automatically called?

toString() gets invoked automatically. Object. toString() 's default implementation simply prints the object's class name followed by the object's hash code which isn't very helpful. So, one should usually override toString() to provide a more meaningful String representation of an object's runtime state.

When toString () method is invoked on an object what is returned?

The toString() method returns the String representation of the object.


1 Answers

To determine whether a method has overridden the default .ToString() check MethodInfo.DeclaringType like so:

void Main()
{
    Console.WriteLine(typeof(MyClass).GetMethod("ToString").DeclaringType != typeof(object));
    Console.WriteLine(typeof(MyOtherClass).GetMethod("ToString").DeclaringType != typeof(object));
}

class MyClass 
{
    public override string ToString() { return ""; }
}

class MyOtherClass {
}

Prints out:

True
False
like image 180
Kirk Woll Avatar answered Sep 19 '22 03:09

Kirk Woll