mishap
mishap

Reputation: 8515

Exception's ToString() method

I found in someones code following :

catch (Exception exception)
{
    Console.WriteLine(exception.ToString());
}

Resharper is graying out the ToString() call which is as always a great suggestion. How does this C# code work without it ? Will ToString() be called implicitly ?

Upvotes: 3

Views: 367

Answers (3)

andypaxo
andypaxo

Reputation: 6641

If the exception is being used within a string... For example "something" + exception.ToString() or String.Format("... {0}", exception), then yes, ToString will be called without you having to call it explicitly.

And... as you updated your example, calling Console.WriteLine() against any object value, ToString will be called. Here's the documentation, with as much detail as you could possibly want.

Upvotes: 5

keyboardP
keyboardP

Reputation: 69372

Console.WriteLine has an overload that takes an object. This object's ToString method is called internally so there's no need for you to add ToString in the first place.

Upvotes: 7

Rich O'Kelly
Rich O'Kelly

Reputation: 41757

I assume the something is string concatenation or used as a parameter in a formatted string, then yes, ToString is called implicitly.

UPDATE FOLLOWING QUESTION UPDATE

Console has an overload of WriteLine that accepts an object argument, in this version on the method ToString is called if the passed instance is not null - R# is aware of this and suggests the choice of the preferable overload.

Upvotes: 3

Related Questions