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# Adding Class Constructors

Why was var used to instantiate in this program and why did the code differ from the video lesson format?

From the video lesson for Instantiation, I understand that the format for instantiation involves use of the keyword new as below:

 Classname objectname = new Classname(); 

So, for example, I thought the code to instantiate here, for a class named Albums, would be:

 Albums album = new Albums(); 

I am wondering why this code contains var at all? I thought the use of the new keyword requires a format as above, and the fact that the object is a variable is understood.

Secondly, is my understanding of the code format required to instantiate an object/instance from a class correct? If not, why not?

For additional context, here's my workspace snapshot: (link)[https://w.trhou.se/o2pm8efq1g]

1 Answer

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there, Ra Bha! There are two ways to declare a variable. You can give it an "implicit type" using var or you can use an "explicit type" which is the data type of the variable being declared. Either is valid. As is so often the case, there is more than one way to do things.

This:

 Albums album = new Albums(); 

is equally as valid as:

 var album = new Albums();

These two are equally valid declarations of strings:

string greeting = "Hello there, ";
var studentName = "Rha Ba";

The only real difference is that we're being very explicit about the type of data in greeting. In studentName we're letting C# figure out the data type for us.

var has not been available in all versions of C#. Personally, I like the more explicit typing, but that's just personal opinion. There can be cases when you will need var over specifying the type explicitly, but that is a discussion further down the road. I'd suggest taking a look at Microsoft's documentation on the var keyword.

Hope this helps! :sparkles: