C
C#•14mo ago
Sonath

Why does the following prints "Point" to the console instead of "(2, 3)"?

Point thing = new Point(2, 3);
System.Console.WriteLine(thing); // prints Point
System.Console.WriteLine(thing.ToString()); // prints (2, 3)

public class Point
{
public int X {get; private set; }
public int Y {get; private set; }

public Point(): this(0, 0)
{

}

public Point(int x, int y)
{
this.X = x;
this.Y = y;
}

// using NEW not OVERRIDE
public new string ToString()
{
return $"({X}, {Y})";
}
}
Point thing = new Point(2, 3);
System.Console.WriteLine(thing); // prints Point
System.Console.WriteLine(thing.ToString()); // prints (2, 3)

public class Point
{
public int X {get; private set; }
public int Y {get; private set; }

public Point(): this(0, 0)
{

}

public Point(int x, int y)
{
this.X = x;
this.Y = y;
}

// using NEW not OVERRIDE
public new string ToString()
{
return $"({X}, {Y})";
}
}
Is it because Console.WriteLine uses an object reference internally?
2 Replies
Angius
Angius•14mo ago
Yes, Console.WriteLine() takes an object So you need to override the object's .ToString() method Rather than hiding it with new
Sonath
SonathOP•14mo ago
alright thank you 😄 it really threw me off cause I always believed that it just executes whatever .ToString exists on the object that's passed, but since it's using object internally it makes sense!

Did you find this page helpful?