C#

#7
TIOBE#5
PYPL#5
GitHub#15
RedMonk#5
IEEESpectrum#7
JetBrains#9
programming languageobject-oriented.NETmicrosoftenterprise

Programming Language

C# (C Sharp)

Overview

C# is an object-oriented programming language developed by Microsoft. It works closely with the .NET Framework and covers a wide range of applications from Windows application development to web development, game development, and cross-platform development.

Details

C# was developed by Anders Hejlsberg and others at Microsoft in 2000, designed as a safer and more productive language while being influenced by Java and C++. It grew alongside the .NET Framework and now supports cross-platform development through .NET Core/.NET 5+.

Features like automatic memory management through garbage collection, strong type system, LINQ (Language Integrated Query), asynchronous programming, and generics enable writing safe and expressive code.

Code Examples

Hello World

using System;

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

// Top-level programs since C# 9.0
using System;

Console.WriteLine("Hello, World!");

Classes and Objects

using System;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    
    // Constructor
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
    
    // Method
    public void Introduce()
    {
        Console.WriteLine($"Hello, I'm {Name}. I'm {Age} years old.");
    }
    
    // Static method
    public static Person CreateAdult(string name)
    {
        return new Person(name, 20);
    }
}

class Program
{
    static void Main()
    {
        var person = new Person("John", 25);
        person.Introduce();
        
        var adult = Person.CreateAdult("Jane");
        adult.Introduce();
    }
}

Properties and Accessors

public class BankAccount
{
    private decimal _balance;
    
    public string AccountNumber { get; }
    
    public decimal Balance 
    { 
        get => _balance;
        private set => _balance = value >= 0 ? value : throw new ArgumentException("Balance cannot be negative");
    }
    
    // Auto property
    public string AccountHolderName { get; set; }
    
    // Read-only property
    public DateTime CreatedDate { get; } = DateTime.Now;
    
    public BankAccount(string accountNumber, string holderName)
    {
        AccountNumber = accountNumber;
        AccountHolderName = holderName;
        Balance = 0;
    }
    
    public void Deposit(decimal amount)
    {
        if (amount > 0)
            Balance += amount;
    }
    
    public bool Withdraw(decimal amount)
    {
        if (amount > 0 && amount <= Balance)
        {
            Balance -= amount;
            return true;
        }
        return false;
    }
}

LINQ (Language Integrated Query)

using System;
using System.Collections.Generic;
using System.Linq;

public class Student
{
    public string Name { get; set; }
    public int Age { get; set; }
    public int Score { get; set; }
}

class Program
{
    static void Main()
    {
        var students = new List<Student>
        {
            new Student { Name = "John", Age = 20, Score = 85 },
            new Student { Name = "Jane", Age = 19, Score = 92 },
            new Student { Name = "Bob", Age = 21, Score = 78 },
            new Student { Name = "Alice", Age = 20, Score = 88 }
        };
        
        // Get high score students
        var highScoreStudents = students
            .Where(s => s.Score >= 85)
            .OrderByDescending(s => s.Score)
            .Select(s => new { s.Name, s.Score });
        
        foreach (var student in highScoreStudents)
        {
            Console.WriteLine($"{student.Name}: {student.Score} points");
        }
        
        // Calculate average score
        var averageScore = students.Average(s => s.Score);
        Console.WriteLine($"Average score: {averageScore:F1} points");
        
        // Group by age
        var groupedByAge = students
            .GroupBy(s => s.Age)
            .Select(g => new { Age = g.Key, Count = g.Count() });
        
        foreach (var group in groupedByAge)
        {
            Console.WriteLine($"Age {group.Age}: {group.Count} students");
        }
    }
}

Asynchronous Programming

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        Console.WriteLine("Fetching data...");
        
        // Call multiple APIs in parallel
        var task1 = FetchDataAsync("https://api.example1.com/data");
        var task2 = FetchDataAsync("https://api.example2.com/data");
        var task3 = FetchDataAsync("https://api.example3.com/data");
        
        var results = await Task.WhenAll(task1, task2, task3);
        
        for (int i = 0; i < results.Length; i++)
        {
            Console.WriteLine($"Result {i + 1}: {results[i]}");
        }
    }
    
    static async Task<string> FetchDataAsync(string url)
    {
        using var client = new HttpClient();
        try
        {
            var response = await client.GetStringAsync(url);
            return response;
        }
        catch (Exception ex)
        {
            return $"Error: {ex.Message}";
        }
    }
}

Generics and Collections

using System;
using System.Collections.Generic;

public class Repository<T> where T : class
{
    private readonly List<T> _items = new List<T>();
    
    public void Add(T item)
    {
        if (item != null)
            _items.Add(item);
    }
    
    public T? GetById(int id) where T : IIdentifiable
    {
        return _items.FirstOrDefault(item => item.Id == id);
    }
    
    public IEnumerable<T> GetAll()
    {
        return _items.AsReadOnly();
    }
    
    public bool Remove(T item)
    {
        return _items.Remove(item);
    }
}

public interface IIdentifiable
{
    int Id { get; }
}

public class Product : IIdentifiable
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public decimal Price { get; set; }
}

class Program
{
    static void Main()
    {
        var productRepo = new Repository<Product>();
        
        productRepo.Add(new Product { Id = 1, Name = "Laptop", Price = 800 });
        productRepo.Add(new Product { Id = 2, Name = "Mouse", Price = 30 });
        
        var allProducts = productRepo.GetAll();
        foreach (var product in allProducts)
        {
            Console.WriteLine($"{product.Name}: {product.Price:C}");
        }
    }
}

Record Types (C# 9.0+)

// Record type definition
public record Person(string FirstName, string LastName, int Age)
{
    public string FullName => $"{FirstName} {LastName}";
}

// Inheritance
public record Employee(string FirstName, string LastName, int Age, string Department) 
    : Person(FirstName, LastName, Age);

class Program
{
    static void Main()
    {
        var person1 = new Person("John", "Doe", 30);
        var person2 = new Person("John", "Doe", 30);
        
        // Value equality
        Console.WriteLine(person1 == person2); // True
        
        // Non-destructive mutation with 'with' expression
        var olderPerson = person1 with { Age = 31 };
        Console.WriteLine($"{olderPerson.FullName}, {olderPerson.Age} years old");
        
        var employee = new Employee("Jane", "Smith", 28, "Development");
        Console.WriteLine($"{employee.FullName}, {employee.Department}");
    }
}

Advantages and Disadvantages

Advantages

  • Strong Type System: High safety through compile-time error detection
  • Rich Development Tools: Powerful development environment with Visual Studio
  • Automatic Memory Management: Memory leak prevention through garbage collection
  • Cross-Platform: Runs on Linux/macOS with .NET Core/.NET 5+
  • Rich Libraries: Extensive library ecosystem in .NET
  • High Productivity: Features like LINQ, async processing, properties

Disadvantages

  • Microsoft Ecosystem Dependency: Primarily used within Microsoft technology stack
  • License Costs: Commercial licenses for Visual Studio and Windows Server
  • Performance: May be slower than native code in some cases
  • Learning Cost: Understanding of object-oriented programming and .NET Framework required

Key Links

Ranking Information

  • Overall Ranking: 7th
  • TIOBE Index: 5th
  • PYPL PopularitY: 5th
  • GitHub Usage: 15th
  • RedMonk Language Ranking: 5th
  • IEEE Spectrum: 7th
  • JetBrains Developer Survey: 9th

C# is a programming language that provides modern features and high productivity, primarily for enterprise development in the Microsoft ecosystem.