C# Language Reference

The C# language is a modern, object-oriented programming language developed by Microsoft. It is a type-safe, component-oriented language that runs on the .NET Framework. C# is designed to offer the power of C++ with the ease of use of Visual Basic.

Note: This section provides a comprehensive reference to the C# language features, syntax, and semantics. For conceptual overviews and practical examples, please refer to the C# Tutorials.

Core Concepts

C# is built around several fundamental programming concepts:

Key Language Features

Variables and Data Types

C# supports a rich set of built-in data types, including:

Example:


int age = 30;
string name = "Alice";
bool isActive = true;
            

Control Flow

Control flow statements allow you to dictate the order in which code is executed.

Example:


for (int i = 0; i < 10; i++)
{
    if (i % 2 == 0)
    {
        Console.WriteLine($"{i} is even.");
    }
}
            

Classes and Objects

Classes define the blueprints for objects, which are instances of those classes. They encapsulate data (fields) and behavior (methods).


public class Person
{
    public string FirstName { get; set; }
    public int Age { get; set; }

    public void Greet()
    {
        Console.WriteLine($"Hello, my name is {FirstName} and I am {Age} years old.");
    }
}

// Usage:
Person person1 = new Person { FirstName = "Bob", Age = 25 };
person1.Greet();
            

Methods

Methods are blocks of code that perform a specific task. They can accept parameters and return values.


public int Add(int a, int b)
{
    return a + b;
}

int sum = Add(5, 3); // sum will be 8
            

Properties

Properties provide a flexible mechanism to read, write, or compute the value of a private field.


public class Product
{
    private decimal _price;

    public decimal Price
    {
        get { return _price; }
        set
        {
            if (value >= 0)
            {
                _price = value;
            }
            else
            {
                throw new ArgumentOutOfRangeException("Price cannot be negative.");
            }
        }
    }
}
            

Advanced Topics

C# offers a wide range of advanced features for building complex and efficient applications:

Tip: Explore the official .NET documentation for detailed API references and examples related to each C# feature.

For a complete list of C# language keywords and their usage, please refer to the C# Keywords page.