Don’t miss these 15 essential Keywords in C#
In C#, keywords are reserved words that have specific meanings within the language and cannot be used as identifiers (names for variables, methods, classes, etc.). These keywords help define the structure and control the flow of a C# program. This guide explores some of the most important C# keywords, explaining their purpose, syntax, and usage.
Embark on a journey of continuous learning and exploration with DotNet-FullStack-Dev. Uncover more by visiting our https://dotnet-fullstack-dev.blogspot.com reach out for further information.
1. abstract
Declares a class or a method as incomplete and must be implemented by derived classes.
public abstract class ClassName { }
public abstract returnType MethodName();
public abstract class Shape
{
public abstract double Area();
}
public class Circle : Shape
{
private double radius;
public Circle(double r) => radius = r;
public override double Area() => Math.PI * radius * radius;
}
2. async
and await
Used to define asynchronous methods and handle asynchronous operations.
public async Task MethodName() { await SomeAsyncMethod(); }
public async Task FetchData()
{
await Task.Delay(2000); // Simulating data fetch
Console.WriteLine("Data fetched!");
}
3. break
Terminates the nearest enclosing loop or switch statement.
break;
for (int i = 0; i < 10; i++)
{
if (i == 5) break;
Console.WriteLine(i);
}
// Output: 0 1 2 3 4
4. const
Declares a constant value that cannot be modified after its declaration.
const datatype variableName = value;
const double Pi = 3.14159;
Console.WriteLine(Pi);
5. continue
Skips the current iteration of a loop and proceeds to the next iteration.
continue;
for (int i = 0; i < 5; i++)
{
if (i == 2) continue;
Console.WriteLine(i);
}
// Output: 0 1 3 4
6. else
Defines an alternative block of code to execute if the if
condition is false.
if (condition) { /* code */ } else { /* alternative code */ }
int number = 5;
if (number > 10)
{
Console.WriteLine("Greater than 10");
}
else
{
Console.WriteLine("Less than or equal to 10");
}
// Output: Less than or equal to 10
7. finally
Executes a block of code after try
and catch
, regardless of whether an exception is thrown.
try { /* code */ } catch (Exception e) { /* handle exception */ } finally { /* cleanup code */ }
try
{
int result = 10 / 0;
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Cannot divide by zero");
}
finally
{
Console.WriteLine("Cleanup operations");
}
8. foreach
Iterates over each element in a collection.
foreach (var item in collection) { /* code */ }
string[] fruits = { "Apple", "Banana", "Cherry" };
foreach (var fruit in fruits)
{
Console.WriteLine(fruit);
}
9. if
Executes a block of code if a specified condition is true.
if (condition) { /* code */ }
int num = 10;
if (num > 5)
{
Console.WriteLine("Number is greater than 5");
}
10. lock
Ensures that one thread does not enter a critical section of code while another thread is in that section.
lock (object) { /* critical section */ }
private static object _lock = new object();
public void WriteData()
{
lock (_lock)
{
// Critical section
Console.WriteLine("Writing data...");
}
}
11. override
Allows a derived class to provide a new implementation of a method defined in the base class.
public override returnType MethodName() { /* new implementation */ }
public class Animal
{
public virtual void Speak() => Console.WriteLine("Animal sound");
}
public class Dog : Animal
{
public override void Speak() => Console.WriteLine("Bark");
}
12. return
Exits a method and optionally returns a value.
return value;
public int Add(int a, int b)
{
return a + b;
}
13. static
Declares a static member, which belongs to the type itself rather than to any specific object.
static datatype variableName;
static returnType MethodName() { /* code */ }
public static class MathUtility
{
public static int Add(int a, int b) => a + b;
}
// Usage
int sum = MathUtility.Add(5, 3);
14. using
Declares a scope that automatically disposes of resources.
using (var resource = new Resource()) { /* code */ }
using (StreamWriter writer = new StreamWriter("file.txt"))
{
writer.WriteLine("Hello, World!");
}
15. void
Specifies that a method does not return a value.
public void MethodName() { /* code */ }
public void DisplayMessage()
{
Console.WriteLine("Hello, World!");
}
Conclusion
C# keywords form the building blocks of the language, guiding the structure and flow of your applications. Understanding how to use these keywords effectively is crucial for writing clean, efficient, and maintainable code. Keep this guide handy as a quick reference for some of the most commonly used C# keywords!