CarComp CarComp - 1 year ago 78
C# Question

How can I determine if an object can ToString into value or type name?

I am writing an interop between a php service and our crm. One of the things I need to do is make sure that simple types get converted ToString() for use later in a json converter.

I am not sure even what the name is for 'simple types' but it can be defined like this... "an object that represents a low level variable type, containing a single value, not a class or anything with executable functions etc"

I've found that int, string, bool, double, and surprisingly enum will ToString() with pretty predictable results.

int x = 0;
bool y = true;
double z = 1.59 // money
CustomEnum theEnum = CustomEnum.somevalue;

x.ToString() results in "0"

y.ToString() results in "true"

z.ToString() results in "1.59"

theEnum.ToString() results in "somevalue"

But if I use this:

List<int> iList = new List<int>();

MyClass theClass = new MyClass();

iList.ToString() results in "System.Collections.Generic.List`1[System.Int32]"
theClass.ToString() results in "STTI.NKI.Interop.MyClass"

I'm not limited to lists. I could have an ExpandoObject, or a class etc.

I understand EXACTLY why this happens, and I want to know if there is a quick way to determine if an object of unknown type will ToString() into an expected value, and not the type name. I find it an antipattern to do something like

switch (theObject.GetType())
case typeof(int):
case typeof(bool):
case typeof(doulble):

I am not sure what the terms are, so googling my answer is proving difficult.

Answer Source

So you want to check whether a type has a overridden ToString method? Why not just check whether the value returned by ToString is equal to the value returned by the default implementation of ToString?

From here, we know the default implementation of ToString is

return GetType().ToString();

So, we can use this to check whether an object has overridden the ToString method:

bool toStringOverridden = someObject.GetType().ToString() !=
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download