MSDN

C# Language Documentation

Welcome to the official Microsoft Developer Network (MSDN) documentation for the C# programming language. This guide provides comprehensive information to help you understand, learn, and master C#.

🚀 Start your C# journey today! Explore our tutorials and examples to build powerful applications.

What is C#?

C# (pronounced "C sharp") is a modern, object-oriented, and type-safe programming language developed by Microsoft. It runs on the .NET framework and is widely used for building a variety of applications, including web applications, desktop applications, mobile apps, games, and cloud services.

C# combines the power and performance of C++ with the ease of use and productivity of Visual Basic. Its design goals include:

  • Simplicity: Easier to learn and use than C++.
  • Object-Oriented: Supports all OOP principles.
  • Type-Safe: Prevents many common programming errors.
  • Component-Oriented: Facilitates building reusable software components.
  • Modern: Continuously evolving with new features.

Getting Started with C#

To begin coding in C#, you'll need a development environment. The most popular choice is Visual Studio.

Installing Visual Studio

Download and install Visual Studio Community Edition (free for individual developers, open-source projects, academic research, and more) from the official Visual Studio website.

Your First C# Program

Let's create a simple "Hello, World!" application:

using System; namespace HelloWorldApp { class Program { static void Main(string[] args) { Console.WriteLine("Hello, World!"); } } }

When you run this program, it will output:

Hello, World!

Variables and Data Types

Variables are used to store data. C# is a strongly-typed language, meaning every variable must have a declared type.

Common Data Types

int age = 30; // Integer string name = "Alice"; // String double price = 99.99; // Floating-point number bool isStudent = true; // Boolean DateTime today = DateTime.Now; // Date and Time

Operators

Operators are symbols that perform operations on variables and values.

Arithmetic Operators

int sum = 10 + 5; // Addition int difference = 10 - 5; // Subtraction int product = 10 * 5; // Multiplication int quotient = 10 / 2; // Division int remainder = 10 % 3; // Modulo

See the Operators documentation for a full list.

Control Flow

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

Conditional Statements (if-else)

int score = 85; if (score >= 90) { Console.WriteLine("Grade: A"); } else if (score >= 80) { Console.WriteLine("Grade: B"); } else { Console.WriteLine("Grade: C or below"); }

Loops (for, while, foreach)

Loops execute a block of code repeatedly.

for (int i = 0; i < 5; i++) { Console.WriteLine("Iteration: " + i); }

Classes and Objects

Classes are blueprints for creating objects. Objects are instances of classes.

public class Dog { public string Name { get; set; } public int Age { get; set; } public Dog(string name, int age) { Name = name; Age = age; } public void Bark() { Console.WriteLine("Woof!"); } } // Creating an object Dog myDog = new Dog("Buddy", 3); Console.WriteLine(myDog.Name); myDog.Bark();

Inheritance

Inheritance allows a class to inherit properties and methods from another class (base class).

public class Animal { public virtual void MakeSound() { Console.WriteLine("Some generic sound"); } } public class Cat : Animal { public override void MakeSound() { Console.WriteLine("Meow!"); } }

Interfaces

Interfaces define a contract that classes can implement. They specify methods, properties, and events without providing an implementation.

public interface IRepository<T> { T GetById(int id); void Add(T entity); void Update(T entity); void Delete(int id); }

Generics

Generics allow you to create types that can work with any data type, providing type safety and code reusability.

public class List<T> { private T[] _items = new T[100]; private int _count = 0; public void Add(T item) { // ... implementation ... } } List<string> names = new List<string>(); names.Add("Alice");

Collections

Collections provide ways to store and manage groups of objects. The .NET framework offers various collection types.

  • List<T>: Dynamically sized array.
  • Dictionary<TKey, TValue>: Key-value pairs.
  • HashSet<T>: Collection of unique elements.
  • Queue<T>: First-in, first-out (FIFO) collection.
  • Stack<T>: Last-in, first-out (LIFO) collection.

Learn more about Collections in C#.

Asynchronous Programming

Asynchronous programming allows your application to perform I/O-bound operations without blocking the main thread, improving responsiveness.

Keywords: async, await.

public async Task<string> DownloadDataAsync(string url) { using (HttpClient client = new HttpClient()) { string result = await client.GetStringAsync(url); return result; } }

LINQ (Language Integrated Query)

LINQ provides a powerful and consistent way to query data from various sources (collections, databases, XML, etc.).

int[] numbers = { 5, 4, 1, 3, 9, 8, 7, 6, 2 }; var largeNumbersQuery = from num in numbers where num >= 5 orderby num descending select num; foreach (var num in largeNumbersQuery) { Console.WriteLine(num); }

Error Handling (Exception Handling)

Use try-catch-finally blocks to handle runtime errors gracefully.

try { // Code that might throw an exception string text = null; Console.WriteLine(text.Length); // This will throw NullReferenceException } catch (NullReferenceException ex) { Console.WriteLine("An error occurred: " + ex.Message); } catch (Exception ex) { Console.WriteLine("An unexpected error occurred: " + ex.Message); } finally { Console.WriteLine("Cleanup operations here."); }

Reflection

Reflection allows you to inspect and manipulate types and their members at runtime. This is useful for developing frameworks, debugging, and dynamic code execution.

Key namespace: System.Reflection.

More Advanced Features

C# continues to evolve with powerful features: