C# (pronounced “C Sharp”) is a modern, object-oriented, and type-safe programming language developed by Microsoft. It is widely used for developing desktop applications, web services, and mobile apps. C# supports multiple programming paradigms, including imperative, declarative, functional, generic, object-oriented, and component-oriented programming.

Few things I like about C# are

  • It’s a simple and easy to learn language.
  • The extensive standard library and ecosystem, including ASP.NET and .NET Core.

Few things I dislike about C# are

  • The language has nullable reference types.
  • It rely on dotnet runtime.
  • I’m not a big fan of object-oriented programming.

Variables

Variables in C# are used to store data which can be manipulated by the program. Here’s how you declare variables:

Syntax and Example:

// Variable declaration
int myNumber = 10;
string myString = "Hello, World!";
bool myBool = true;

// Constant declaration
const double PI = 3.14159;

// Type inference using var
var myVar = "This is inferred as a string";

Control Statements

Control statements in C# direct the flow of the program execution based on conditions. Common control statements include if, switch, for, foreach, while, and do-while.

Syntax and Example:

// If statement
if (x > 0)
{
    Console.WriteLine("x is positive");
}

// For loop
for (int i = 0; i < 10; i++)
{
    Console.WriteLine(i);
}

// foreach loop
string[] days = {"Monday", "Tuesday", "Wednesday"};
foreach (string day in days)
{
    Console.WriteLine(day);
}

// While loop
while (x > 0)
{
    Console.WriteLine(x);
    x--;
}

// Switch statement
switch (day)
{
    case "Monday":
        Console.WriteLine("It's Monday!");
        break;
    case "Tuesday":
        Console.WriteLine("It's Tuesday!");
        break;
    default:
        Console.WriteLine("It's not Monday or Tuesday");
        break;
}

Functions

Functions in C# are blocks of code that perform a specific task and can be called from other points in a program.

Syntax and Example:

// Function declaration
public int Add(int a, int b)
{
    return a + b;
}
// Function call
int result = Add(5, 3);
Console.WriteLine(result);

// Anonymous functions
Func<int, int, int> add = (x, y) => x + y;

// Function with multiple return values
public (int, int) GetMinMax(int[] numbers)
{
    int min = numbers.Min();
    int max = numbers.Max();
    return (min, max);
}
var (min, max) = GetMinMax(new int[] {1, 2, 3, 4, 5});

Data Structures (Classes)

Classes in C# are data structures that can contain data members (fields and properties) and function members (methods, constructors).

Syntax and Example:

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

    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }

    public void SayHello()
    {
        Console.WriteLine("Hello, my name is " + Name);
    }
}

// Creating an instance of a class
Person person = new Person("Alice", 30);
// Accessing fields and methods
Console.WriteLine(person.Name);
person.SayHello();

In C# the classes define an object with values and methods. The object is an instance of the class.

Interfaces

Interfaces in C# define a contract that classes can implement, specifying a set of methods that the implementing type must contain.

Syntax and Example:

public interface IShape
{
    double Area();
    double Perimeter();
}

// Implementing the interface
public class Circle : IShape
{
    public double Radius { get; set; }

    public double Area()
    {
        return Math.PI * Radius * Radius;
    }

    public double Perimeter()
    {
        return 2 * Math.PI * Radius;
    }
}

Collection Manipulation

C# provides a variety of collection types, such as arrays, lists, dictionaries.

Syntax and Example:

// Array
int[] numbers = {1, 2, 3, 4, 5};

// List
List<int> numbers = new List<int> {1, 2, 3, 4, 5};
// Iterating through a list
foreach (int number in numbers)
{
    Console.WriteLine(number);
}
// Adding to a list
numbers.Add(6);
// Removing from a list
numbers.Remove(3);

// Dictionary
Dictionary<string, int> ages = new Dictionary<string, int>
{
    {"Alice", 25},
    {"Bob", 30}
};

// Accessing dictionary values
Console.WriteLine(ages["Alice"]);
// Iterating through a dictionary
foreach (var pair in ages)
{
    Console.WriteLine(pair.Key + " is " + pair.Value + " years old");
}
// Adding to a dictionary
ages["Charlie"] = 35;
// Removing from a dictionary
ages.Remove("Bob");

Linq (Language Integrated Query)

LINQ is a set of features that extends powerful query capabilities to the C# language, allowing you to easily retrieve data from arrays, XML, databases, and more with a SQL-like syntax.

Syntax and Example:

int[] numbers = {1, 2, 3, 4, 5};

var evenNumbers = from number in numbers
                  where number % 2 == 0
                  select number;

Error Handling

Error handling in C# is accomplished using try-catch blocks, allowing you to catch exceptions that occur during program execution.

Syntax and Example:

// throwing an exception
public void DoSomething()
{
    throw new Exception("Something went wrong");
}

// catching an exception
try
{
    DoSomething();
}
catch (Exception e)
{
    Console.WriteLine("Error: " + e.Message);
}
finally
{
    Console.WriteLine("Finished execution");
}

Concurrency

C# supports concurrent programming primarily through the System.Threading and System.Threading.Tasks namespaces, enabling multi-threading and asynchronous programming.

Syntax and Example:

using System.Threading.Tasks;

public class Example
{
    public static async Task DoWorkAsync()
    {
        await Task.Run(() =>
        {
            // Simulate long-running task
            Thread.Sleep(1000);
            Console.WriteLine("Work completed");
        });
    }

    // Using Task.WaitAll()
    public static void Main()
    {
        Task t1 = DoWorkAsync();
        Task t2 = DoWorkAsync();
        Task.WaitAll(t1, t2);
    }
}

Ecosystem

Installation

.NET can be installed from the official .NET download page or using package managers like Homebrew on macOS.

brew install --cask dotnet

Hello World

using System;

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

CLI

  • dotnet new console -n <project-name>: Create a new console project
  • dotnet run: Build and run the .NET project
  • dotnet build: Build a .NET project
    • dotnet build --runtime ubuntu.20.04-x64 for Linux
    • dotnet build --runtime win10-x64 for Windows
    • dotnet build --runtime osx.10.15-x64 for macOS
  • dotnet test: Run tests in the project
  • dotnet fmt: Format the code (requires installing a tool like dotnet-format)
  • dotnet add package <package-name>: Add a NuGet package to the project

Package Management

NuGet is the package manager for .NET. It is integrated into the .NET CLI with commands like:

  • dotnet add package <package-name> - Add a NuGet package to the project
  • dotnet remove package <package-name> - Remove a NuGet package from the project
  • dotnet restore - Restore the dependencies and tools of a project
  • ASP.NET Core - Open-source framework for web apps and services
  • Entity Framework Core - Modern object-database mapper for .NET
  • xUnit - Testing framework for .NET
  • Serilog - Diagnostic logging library for .NET applications
  • Automapper - A convention-based object-object mapper
  • MediatR - Simple, unambitious mediator implementation in .NET

Special Features

  • LINQ (Language Integrated Query): A set of features that extends powerful query capabilities to the C# language, allowing you to easily retrieve data from arrays, XML, databases, and more with a SQL-like syntax.
  • Async/Await: Simplifies asynchronous programming, allowing you to write asynchronous code that is as straightforward as synchronous code without complex callbacks or manual thread management.