C# Language Reference
Welcome to the comprehensive C# language reference. This section provides detailed information about the C# programming language, its syntax, features, and best practices.
Introduction to C#
C# is a modern, object-oriented, and type-safe programming language developed by Microsoft. It is designed for building a wide range of applications on the .NET platform, including web applications, desktop applications, mobile apps, cloud services, and games.
C# Keywords
Keywords are reserved words that have special meaning in the C# language. They cannot be used as identifiers (names for variables, methods, classes, etc.). Here is a list of common C# keywords:
abstract, as, base, bool, break, byte, case, catch, char, checked, class, const, continue, decimal, default, delegate, do, double, else, enum, event, explicit, extern, false, finally, fixed, float, for, foreach, goto, if, implicit, in, interface, internal, is, lock, long, namespace, new, null, object, operator, out, override, params, private, protected, public, readonly, ref, return, sbyte, sealed, short, sizeof, stackalloc, static, string, struct, switch, this, throw, true, try, typeof, uint, ulong, unchecked, unsafe, ushort, using, virtual, void, volatile, while
Operators
Operators are special symbols that perform operations on one or more operands. C# supports various types of operators, including arithmetic, relational, logical, assignment, and more.
Arithmetic Operators
Used for mathematical calculations:
+(Addition)-(Subtraction)*(Multiplication)/(Division)%(Modulus)++(Increment)--(Decrement)
Data Types
C# is a strongly-typed language, meaning that every variable and expression has a type that is known at compile time. This helps prevent errors and improve code readability.
Primitive Types
These are the built-in types provided by C#:
- Integral types:
sbyte,byte,short,ushort,int,uint,long,ulong - Floating-point types:
float,double,decimal - Boolean type:
bool - Character type:
char
Reference Types
Variables of reference types store references to objects in memory. Examples include classes, interfaces, delegates, arrays, and strings.
string greeting = "Hello, World!";
int[] numbers = { 1, 2, 3, 4, 5 };
MyClass myObject = new MyClass();
Nullable Types
Nullable types allow you to assign null to value types. They are declared with a ? suffix.
int? nullableInt = null;
if (nullableInt.HasValue) {
Console.WriteLine(nullableInt.Value);
}
Classes and Structs
Classes and structs are user-defined types that encapsulate data and behavior. Classes are reference types, while structs are value types.
public class Person {
public string Name { get; set; }
public int Age { get; set; }
public void Introduce() {
Console.WriteLine($"Hello, my name is {Name} and I am {Age} years old.");
}
}
public struct Point {
public int X { get; set; }
public int Y { get; set; }
}
Interfaces
Interfaces define a contract that classes can implement. They specify a set of methods, properties, events, or indexers that a class must provide.
public interface IDrawable {
void Draw();
}
public class Circle : IDrawable {
public void Draw() {
Console.WriteLine("Drawing a circle.");
}
}
Inheritance
Inheritance allows a class to inherit properties and methods from another class (the base class), promoting code reuse and establishing an "is-a" relationship.
public class Animal {
public virtual void Speak() {
Console.WriteLine("Some generic animal sound.");
}
}
public class Dog : Animal {
public override void Speak() {
Console.WriteLine("Woof!");
}
}
Polymorphism
Polymorphism means "many forms." It allows objects of different classes to be treated as objects of a common base class. This is achieved through method overriding and overloading.
Generics
Generics provide a way to create types and methods that operate on a specified type without needing to know the specific type at compile time. This enhances type safety and performance.
public class List {
private T[] items;
// ...
}
List intList = new List();
List stringList = new List();
Delegates
Delegates are type-safe function pointers. They can be used to pass methods as arguments to other methods or to store methods in a variable.
public delegate void MyDelegate(string message);
public void PrintMessage(string msg) {
Console.WriteLine(msg);
}
MyDelegate delegateInstance = PrintMessage;
delegateInstance("Hello from delegate!");
Events
Events are a mechanism for a class to notify other classes when something significant happens. They are typically implemented using delegates.
public class Button {
public event EventHandler Click;
public void SimulateClick() {
Click?.Invoke(this, EventArgs.Empty);
}
}
Attributes
Attributes provide declarative information about code elements. They can be applied to classes, methods, properties, etc., and are used by the .NET runtime or other tools.
[Serializable]
public class MyData {
// ...
}
Exception Handling
Exception handling is a mechanism to deal with runtime errors. The try, catch, and finally blocks are used to handle exceptions gracefully.
try {
int result = 10 / 0;
} catch (DivideByZeroException ex) {
Console.WriteLine($"Error: {ex.Message}");
} finally {
Console.WriteLine("This will always execute.");
}
LINQ (Language Integrated Query)
LINQ allows you to write queries against data sources directly within the C# language, providing a consistent and powerful way to query collections, databases, XML, and more.
var numbers = new int[] { 1, 5, 2, 8, 3 };
var evenNumbers = from num in numbers
where num % 2 == 0
select num;
Async/Await
The async and await keywords simplify asynchronous programming, allowing you to write non-blocking code that remains responsive, especially for I/O-bound operations.
public async Task GetDataAsync() {
// Simulate network delay
await Task.Delay(1000);
return "Some fetched data.";
}
Unsafe Code
C# allows you to write "unsafe" code, which bypasses the .NET type safety mechanisms. This is typically used for low-level memory manipulation and interop with native code. It requires the `AllowUnsafeHeader` compiler option.
Important Note
This is a simplified overview. For detailed specifications and advanced topics, please refer to the official Microsoft C# documentation.