In C#, contextual keywords are a special type of keywords that provide specific meaning within a particular context in your code, but unlike regular keywords (for example- class
, interface
and int
), they are not reserved words. This means you can use them as identifiers outside of that specific context.
These are some of the contextual keywords you should know:
and
– The keywordand
was introduced in C# 9 for pattern matching. It allows you to combine multiple patterns, requiring all of them to match for the code to proceed. In other words, It’s similar to&&
operator that we use in conditional expressions.
ascending
– The keywordascending
is used specifically within query expressions. It indicates that you want to sort the results of the query in ascending order, from smallest to largest.
async
&await
– Theasync
andawait
keywords are a powerful combination for writing asynchronous code. They allow your program to perform long-running operations without blocking the main thread, making your application more responsive and efficient. Once a method is declared asasync
, you can useawait
within its body.
dynamic
– Thedynamic
keyword is used to declare variables or method parameters that can hold objects of any type at runtime. It bypasses static type checking at compile time, offering more flexibility but it also sacrifices some of the safety benefits of a statically typed language like C#.
equals
– Theequals
keyword is used to compare two objects for equality. It’s similar to==
operator that we use in conditional expressions.
into
– Theinto
keyword is used specifically within query expressions. It allows you to store the results of agroup
,join
, orselect
clause into a new temporary variable. This variable can then be used for further operations within the query expression.
nameof
– Thenameof
keyword is a handy tool introduced in C# 6.0. It allows you to get the name of a variable, method, type, or other program element as a string literal at compile time.
partial
– Thepartial
keyword is used to define a class, struct, or interface across multiple source files. This allows you to logically separate the functionality of a type while maintaining it as a single entity during compilation.
var
– Thevar
keyword is used for implicit type declaration of variables. It allows the compiler to infer the data type of the variable based on the value assigned during initialization.
with
– Thewith
keyword was introduced in C# 10 for creating modified copies of objects. Thewith
expression allows you to create a new object that’s a copy of an existing object, with specific properties or fields modified.
So these were some of the contextual keywords we use in C#. Some other notable contextual keywords include global
, join
, record
and yield
.
Do let me know in the comment section what other contextual keywords you know about.
Pingback: Why C# Developers Should Love TypeScript (and Vice Versa) 🍔
Pingback: String Methods in C#: Everything you need to know