C# Programming Guide
Introduction to C#
C# (pronounced "C sharp") is a modern, object-oriented, and type-safe programming language developed by Microsoft. It is designed to enable developers to build a wide range of applications for the Microsoft .NET platform, from web services and desktop applications to mobile apps and games.
C# combines the high productivity of a component-oriented language with the raw power and flexibility of C-like languages. It has a rich type system and an extensive library that supports common programming tasks.
Key Features: Type-safe, object-oriented, component-oriented, strongly typed, garbage collection, generics, asynchronous programming.
Getting Started
To begin programming in C#, you'll need to install the .NET SDK. This includes the C# compiler and the necessary runtime environment.
- Download and Install .NET SDK: Visit the official .NET download page.
- Choose an IDE: Visual Studio (Community, Professional, Enterprise) or Visual Studio Code with the C# Dev Kit extension are popular choices.
- Create Your First Project: Open your IDE, create a new Console Application project, and write your first "Hello, World!" program.
// Hello, World! Program
using System;
public class HelloWorld
{
public static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
Basic Concepts
Understanding the fundamental building blocks of C# is crucial for effective programming.
Variables and Data Types
Variables are named storage locations that hold data. C# is statically typed, meaning the type of a variable must be declared explicitly.
| Type | Description | Example |
|---|---|---|
int |
32-bit signed integer. | int age = 30; |
string |
Sequence of characters. | string name = "Alice"; |
double |
64-bit floating-point number. | double price = 99.99; |
bool |
True or false value. | bool isComplete = false; |
Operators
Operators are symbols that perform operations on variables and values.
- Arithmetic:
+,-,*,/,% - Comparison:
==,!=,>,<,>=,<= - Logical:
&&(AND),||(OR),!(NOT) - Assignment:
=,+=,-=
Control Flow Statements
Control flow statements determine the order in which code is executed.
- Conditional:
if,else if,else,switch - Loops:
for,while,do-while,foreach - Branching:
break,continue,return
if (score > 90)
{
Console.WriteLine("Excellent!");
}
else if (score > 70)
{
Console.WriteLine("Good.");
}
else
{
Console.WriteLine("Needs Improvement.");
}
for (int i = 0; i < 5; i++)
{
Console.WriteLine($"Iteration: {i}");
}
Object-Oriented Programming (OOP)
C# is a powerful object-oriented language. OOP paradigms help in organizing code into reusable and maintainable modules.
Classes and Objects
A class is a blueprint for creating objects. An object is an instance of a class.
public class Car
{
public string Model;
public int Year;
public void StartEngine()
{
Console.WriteLine($"The {Model}'s engine is starting.");
}
}
// Creating an object (instance) of the Car class
Car myCar = new Car();
myCar.Model = "Sedan";
myCar.Year = 2023;
myCar.StartEngine(); // Output: The Sedan's engine is starting.
Inheritance
Inheritance allows a new class (derived class) to inherit properties and methods from an existing class (base class).
public class Vehicle {}
public class Truck : Vehicle { /* Truck inherits from Vehicle */ }
Polymorphism
Polymorphism means "many forms." It allows objects of different classes to be treated as objects of a common base class.
Achieved through method overriding and interfaces.
Encapsulation
Encapsulation is the bundling of data (fields) and methods that operate on the data within a single unit (class). It also involves controlling access to the data using access modifiers (public, private, protected).
Advanced Topics
Generics
Generics provide a way to define type-safe classes, interfaces, and methods that can operate on different types without compromising type safety.
// Generic list
List<int> numbers = new List<int>();
numbers.Add(10);
List<string> names = new List<string>();
names.Add("Bob");
Delegates and Events
Delegates are type-safe function pointers. Events are a mechanism that allows a class to notify other classes when something happens.
Asynchronous Programming
The async and await keywords simplify writing asynchronous code, allowing applications to remain responsive while performing long-running operations.
public async Task<string> DownloadDataAsync(string url)
{
using (HttpClient client = new HttpClient())
{
string result = await client.GetStringAsync(url);
return result;
}
}
Newer Language Features
C# continuously evolves with new features introduced in various versions:
- LINQ (Language Integrated Query)
- Lambda Expressions
- Extension Methods
- Pattern Matching
- Record Types
- Nullable Reference Types
- Top-level Statements
- Record Structs
Best Practices
Follow these guidelines for robust and maintainable C# code:
- Use meaningful names for variables, methods, and classes.
- Adhere to naming conventions (e.g., PascalCase for classes and methods, camelCase for local variables).
- Write clear, concise code with appropriate comments where necessary.
- Utilize modern C# features to improve readability and efficiency.
- Handle exceptions gracefully.
- Strive for immutability where appropriate.
- Write unit tests to ensure code correctness.