Question

I have a custom class structure as follows.

public interface Stuff { }
public Thing : Stuff 
{ 
  public new String ToString() { return "That's the thing!"; } 
}

Then, in other parts of my code I have a method that takes a String object as a parameter. The first line compiles, while the second one doesn't. I thought that ToString was called by default when sending in an object. And Stuff, being inherited from Object class should have ToString already implemented (and also, in my case, shadowed by my implementation).

Thing thing = new Thing();
MustHaveString(thing.ToString());
MustHaveString(thing);

What do I miss?

Was it helpful?

Solution 2

Assuming MustHaveString looks something like:

public void MustHaveString(string arg)

Then simply saying thing results in a compile error, unless thing has an implicit conversion to string. Without the implicit conversion, you must do thing.ToString(). If, however, your code is like:

string myString = "This is a thing: " + thing;

Then the ToString is implicitly called, so it's optional.

In most cases, I would recommend explicitly calling the ToString method, to make it clear to people reading your code what's going on.

Edit: since this answer was accepted, I thought I should also mention that you should make your ToString() method an override, not a new. This will result in the normally-expected behavior, which is what I described above.

OTHER TIPS

You're probably getting confused because of calls such as String.Format and Console.WriteLine, as well as string concatenation operator, which call ToString implcitly.

This isn't a general rule though. In general, if you need a string, you need to either call ToString explicitly or have some other conversion. I wouldn't recommend creating implicit conversions to string - they're likely to cause more pain than joy.

I'd also recommend against creating a new ToString method. Instead, you should override the one declared by object. Hiding methods is almost always a bad idea; there are a few cases where you really want to do it (e.g. to change the return type) but it should be avoided where possible.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top