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#

Evan Welch
Evan Welch
1,815 Points

Can const variables not be changed?

What is the significance of a const variable as opposed to a standard private variable?

Thank you!

1 Answer

Simon Coates
Simon Coates
8,223 Points

An explanation of const occurs at https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/const. There's also a readonly modifier. Usually you lock down access and try and make things as predictable as possible. I assume both const and private fields are ultimately for really making things predictable, and making sure the value is what you think it is. There's some discussion I found useful at https://www.c-sharpcorner.com/UploadFile/0c1bb2/read-only-and-constant-in-C-Sharp/ . I think C# want you to be sure that a const is a constant by definition (eg. pi). Some compiled languages replace references to constants with values during the compile step and can create dangerous inconsistencies if the value changes and you don't recompile everything.