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#

Pratham Patel
Pratham Patel
4,976 Points

In C# object oriented programming when you create an instance and you give it a data type do you use the classes name as

When you create an instance of a class is the type the same as the classes name

2 Answers

Yes, when you create an instance of a class (also known as an object), the type should be the same as the classes name. This is because classes are simply other data types. All classes are data types. For example, string is a class and therefore a data type. Int is a class, and therefore a data type. A List is a class, and therefore a data type. Make sense?

So, say you have a class called "Student". When you want to instantiate a new student, you want it to be of class Student, which is the same as saying you want it to be of type Student. So, you say something like:

Student newStudent = new Student();
Ryan Sheppard
Ryan Sheppard
2,866 Points

While this is a good general-rule-of-thumb for beginners, it's worth pointing out instance type name and assignment type name won't necessarily always be the same if:

  • The instance type is an interface implemented by the assignment type
// Apple implements IFruit
IFruit fruit = new Apple();
  • The instance type is a parent class of the assignment type
// Apple inherits from Fruit
Fruit fruit = new Apple();

Yes Ryan, I was debating whether or not to include those concepts here... chose not to ;)