Reserved Keywords in C# – Part #1

Reserved Keywords in C#

Hi there,

Today I want to talk about some less common/more advanced reserved keywords in C# and how and when to use them.

Everybody knows that you can’t use words like public, double, for, const in your code to name variables, classes, etc. because they are the so-called reserved words.

 

According to Wikipedia, a reserved word (aka a reserved identifier) in computer science is a word that cannot be used as an identifier, such as the name of a variable, function, or label – it is “reserved from use”

 

Every language has different reserved words, but many of them are the same for a certain group of languages (e.g. C# and Java). In this post, I want to focus on a few reserved keywords in C# that I found interesting.

 

Reserved Keywords in C#

 

decimal – is a variable type that is used to specify monetary values because it has more precision than float and can store 28-29 significant digits.

Read more about the decimal keyword here

 

volatilethis keyword is used for class or struct fields. We use it when we want to tell the compiler that our field may be modified by multiple threads that are executing at the same time. Using the keyword stops compiler optimization and the expected value is stored in the field all the time. You can find more info here.

 

lock – this keyword is used in a statement that makes a block of code runnable by only one thread at a time. A good example would be when you want to withdraw money from an account – this would prevent overdrawing since each withdrawal would need to be done in order. The lock statement takes an argument that should be a reference to an object. The curly braces define the scope of the lock statement. Learn more about the lock here.

 

sealed –  it is used before a class name and prevents other classes from inheriting from the sealed class. The following example shows that class Secretary inherits from Employee class, but any other class cannot inherit from the Secretary class.

 

 

Final Thought 

C# has also a few identifiers that are not reserved per se, for example, await, async, alias, remove, select, var, where, join, dynamic, ascending, so theoretically you could use them, but it’s not recommended and should be avoided because they also have their own meaning and functionality in the code.