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#

Syed Abbas
Syed Abbas
4,762 Points

Objects

Hi, I have a question about objects in C#. To create an object to access fields, methods and properties of a class I need to use the 'new' keyword. When I use a class as a type and a parameter in a method, I just declare the type and name of the object and then use it in the method. Why don't I need to use the 'new' keyword there?

3 Answers

andren
andren
28,558 Points

When you declare a class as a parameter you are telling C# "This method requires that an object of this class is passed in to it". And when you reference that parameter within your code you are referencing the object that was passed in when the method was called.

That means that you aren't actually creating an object, you are just specifying that an object is required. And then referencing that object in your code. When you actually call that method you will have to create an object to pass into it, and at that point the new keyword will be used.

So new is always used when creating the object from scratch, but not when an existing object is being passed around.

Syed Abbas
Syed Abbas
4,762 Points

Thank you very much. I am new to treehouse so I don't know how to give points. Please can you tell me?

andren
andren
28,558 Points

Each answer has a box on the top of its right side that shows its score. To upvote an answer you simply click on the up arrow that is placed above the score.

There should also be a button that allows you to mark an answer as the "Best Answer" which provides the user that posted it with 12 points.