Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

C# C# Objects Object-Oriented Programming Practice Writing Classes

Andrew Miller
Andrew Miller
14,295 Points

Constructor name needs to be same as the Class

Hi All!

I am wondering if the constructor has to be the same name as the class and can a class have multiple constructors. Could I have something like the following: class Point { public readonly int X; public readonly int Y;

public Coordinate (int x, int y)
{
  X = x;
  Y = y;
}

some other constructor...

}

2 Answers

Steven Parker
Steven Parker
221,254 Points

The answer to both questions is "yes". The constructor name must be the same as the class, and you can have more than one using overloading.

It's quite common to have a default constructor that requires no arguments, but an additional one that takes one or more arguments to establish an initial state when an instance is created. I'm pretty sure you'll see examples of this later in the course or in one of the more advanced courses.

Andrew Miller
Andrew Miller
14,295 Points

Thank you for the response. Very helpful.

Yes, Constructor name must be the same as the class. You will also learn that when declaring private variables must of the times you need Set() and Get() methods. However, when building a constructor you can skip the Set method() and store the values in the constructor and get the result with the Get method().