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# 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
229,005 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().