Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C#

Evan Welch
Evan Welch
1,815 Points

How does the computer know that we are using .ToString when we never write ".ToString"?

I understand that we overrided the ToString method for the Point class, and I figured out how Invader.Location relates to the Point class. Still though, we never explicitly referenced .ToString, we just assumed "this" and "Invader.Location" would use .ToString. How does the computer know to use the .ToString method?

2 Answers

Simon Coates
Simon Coates
8,377 Points

Not sure you've successfully linked your request to the lecture content, so it's going to be difficult to ascertain what context you're asking the question in. If you're concatenating, I think it just knows. For instance,

using System;

class MainClass {
  public static void Main (string[] args) {
    var p = new P();
    Console.WriteLine ("Hello World"+ p); // produces "Hello WorldThis is some string"
  }
}

public class P{
  public override String ToString()
  {
    return "This is some string";
  }
}

Otherwise, you might care to post a URL to the course content so the context is specific.

Evan Welch
Evan Welch
1,815 Points

It is in the context of concatenating. Makes perfect sense!