Why do I need to cast a passed object as its type before I can access its values?

Hey guys, I'm a beginner trying to learn C# from The Yellow Book. It's great, but I'm completely stumped by this one paragraph.

We have a class:

class Point { public int x; public int y; public override bool Equals(object obj) { Point p = (Point) obj; if ( ( p.x == x ) && ( p.y == y ) ) { return true; } else { return false; } } 

My questions:

What is happening with the line:

Point p = (Point) obj; 

Why can't we just use "obj.x", and what syntax is being used by placing the class name in parentheses? I believe I understand the point of the exercise (the need to override the default Equals method), so that is not my question.

I'm sorry if I'm not using correct terminology, I'm very new! Thanks so much in advance!

by nmacklin via /r/csharp

Leave a Reply