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 trialChristine Martino
16,837 PointsValue assignment after a closing curly brace? Why does this syntax work?
For context: I come from a heavy Javascript background, so seeing an assignment occur immediately after a closing curly brace kind of boggles my mind. The linter inside my brain is short-circuiting! :P
I'm interested to know if anyone has insight into why this works? Is this only possible with Properties? Thanks!
namespace Treehouse.CodeChallenges
{
class CountDown
{
public int StartAt { get; private set; } = 10; // <-- Why is this valid syntax?
}
}
1 Answer
Fredrik Rönnehag
2,342 PointsWhen creating the property you can give it a default value when you create it. This can be good when you need a starting value and then later subtracting or adding to that within the class and subclasses. This way you can just go back to the property and change the value in order to change the program, rather than go through all methods.
To answer why it works after the curly bracers is because the code isn't ended yet, since the semicolon comes after 10.
class Bottle
{
public int Quantity { get; set; } = 30; // Setting the default value to 30
}
class Program
{
static void Main()
{
Bottle bottle = new Bottle();
Console.WriteLine(bottle.Quantity); // Will show the default value of 30.
bottle.Quantity *= 2;
Console.WriteLine(med.Quantity); // Will multiply the default vaule by 2, showing 60.
}
}