{"id":19846541,"url":"https://github.com/ssukhpinder/csharp-cheatsheet","last_synced_at":"2025-10-27T04:03:57.787Z","repository":{"id":228315648,"uuid":"773642709","full_name":"ssukhpinder/csharp-cheatsheet","owner":"ssukhpinder","description":"C#: From Fundamentals to Advanced Techniques — A Comprehensive Cheat Sheet","archived":false,"fork":false,"pushed_at":"2024-03-18T06:12:51.000Z","size":8,"stargazers_count":5,"open_issues_count":1,"forks_count":3,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-02-28T22:52:14.801Z","etag":null,"topics":["aspnet","aspnetcore","coding","csharp","dotnet","dotnet-core","microsoft","programming"],"latest_commit_sha":null,"homepage":"https://medium.com/c-sharp-progarmming","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ssukhpinder.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null},"funding":{"github":"ssukhpinder","buy_me_a_coffee":"sukhpindersingh","custom":"https://medium.com/c-sharp-progarmming"}},"created_at":"2024-03-18T06:10:31.000Z","updated_at":"2025-02-17T20:42:53.000Z","dependencies_parsed_at":"2024-03-18T07:28:20.185Z","dependency_job_id":"0bfc429b-10f5-4f34-9fdc-9b9c1f20287a","html_url":"https://github.com/ssukhpinder/csharp-cheatsheet","commit_stats":null,"previous_names":["ssukhpinder/csharp-cheatsheet"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/ssukhpinder/csharp-cheatsheet","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ssukhpinder%2Fcsharp-cheatsheet","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ssukhpinder%2Fcsharp-cheatsheet/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ssukhpinder%2Fcsharp-cheatsheet/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ssukhpinder%2Fcsharp-cheatsheet/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ssukhpinder","download_url":"https://codeload.github.com/ssukhpinder/csharp-cheatsheet/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ssukhpinder%2Fcsharp-cheatsheet/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":260370368,"owners_count":22998817,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["aspnet","aspnetcore","coding","csharp","dotnet","dotnet-core","microsoft","programming"],"created_at":"2024-11-12T13:11:45.986Z","updated_at":"2025-10-27T04:03:57.724Z","avatar_url":"https://github.com/ssukhpinder.png","language":null,"readme":"The comprehensive C# Cheat Sheet is designed to aid developers in mastering key syntax and concepts related to C# programming.\n\n## Contents\n\n 1. Basic Structure\n\n 2. Data Types\n\n 3. Variables\n\n 4. Constants\n\n 5. Conditional Statements\n\n 6. Loops\n\n 7. Arrays\n\n 8. Lists\n\n 9. Dictionaries\n\n 10. Methods\n\n 11. Classes \u0026 Objects\n\n 12. Exception Handling\n\n 13. Delegates, Events \u0026 Lambdas\n\n 14. LINQ (Language-Integrated Query)\n\n 15. Attributes\n\n 16. Async/Await\n\n 17. Miscellaneous\n\n 18. String Manipulation\n\n 19. File I/O\n\n 20. Date \u0026 Time\n\n 21. Generics\n\n 22. Nullables\n\n 23. Attributes \u0026 Reflection\n\n 24. Extension Methods\n\n 25. Dependency Injection\n\n 26. Partial Classes\n\n 27. Interoperability\n\n 28. Anonymous Types\n\n 29. Tuples\n\n 30. Pattern Matching\n\n 31. Local Functions\n\n 32. Records\n\n 33. with Expressions\n\n 34. Indexers and Ranges\n\n 35. using Declaration\n\n 36. Nullable Reference Types (NRTs)\n\n 37. Pattern-Based Using\n\n 38. Property Patterns\n\n 39. Default Interface Implementations\n\n 40. Dynamic Binding\n\n## 1. Basic Structure\n\nAll C# programs follow a fundamental structure, outlined below:\n```\n    using System;\n    \n    public class HelloWorld\n    {\n        public static void Main(string[] args)\n        {\n            Console.WriteLine(\"Hello, World!\");\n        }\n    }\n```\nStarting with .NET 5, top-level statements simplify the Program.cs content:\n```\n    Console.WriteLine(\"Hello, World\");\n```\n## 2. Data Types\n\nC# supports various data types such as:\n\n* Value Types: int, char, float\n\n* Reference Types: string, class, array\n\n## 3. Variables\n\nVariables are symbolic names for values:\n```\n    int age = 30; // integer variable\n    string name = \"John\"; // string variable\n    double PI = 3.14159; // double for floating-point numbers\n    bool isLoggedIn = true; // boolean variable\n```\nUse ‘var’ for type inference:\n```\n    var number = 5; // compiler infers type as int\n    var message = \"This is a message\"; // compiler infers type as string\n```\n## 4. Constants\n\nConstants hold immutable values:\n```\n    const double GRAVITY = 9.81; // constant for gravitational acceleration\n    const string COMPANY_NAME = \"MyCompany\"; // constant company name\n```\n## 5. Conditional Statements\n\nControl program flow based on conditions:\n```\n    int age = 20;\n    \n    if (age \u003e= 18)\n    {\n        Console.WriteLine(\"You are eligible to vote.\");\n    }\n    else\n    {\n        Console.WriteLine(\"You are not eligible to vote.\");\n    }\n    \n    switch (variable) { /*...*/ } // Switch statement\n```\n## 6. Loops\n\nExecute code repeatedly:\n```\n    for (int i = 1; i \u003c= 5; i++)\n    {\n        Console.WriteLine(i);\n    }\n    \n    foreach (var item in collection) { /*...*/ } // Foreach loop\n    \n    while (condition) { /*...*/ } // While loop\n    \n    do { /*...*/ } while (condition); // Do-while loop\n```\n## 7. Arrays\n\nFixed-size collections of elements:\n```\n    string[] names = new string[3] { \"Alice\", \"Bob\", \"Charlie\" };\n    Console.WriteLine(names[1]); // Output: Bob (accessing element at index 1)\n```\n## 8. Lists\n\nDynamic collections similar to arrays:\n```\n    List\u003cint\u003e numbers = new List\u003cint\u003e();\n    numbers.Add(1);\n    numbers.Add(2);\n    numbers.Add(3);\n    \n    foreach (var number in numbers)\n    {\n        Console.WriteLine(number);\n    }\n```\n## 9. Dictionaries\n\nKey-value pairs for data association:\n```\n    Dictionary\u003cstring, string\u003e phonebook = new Dictionary\u003cstring, string\u003e();\n    phonebook.Add(\"John Doe\", \"123-456-7890\");\n    phonebook.Add(\"Jane Doe\", \"987-654-3210\");\n    \n    Console.WriteLine(phonebook[\"John Doe\"]); // Output: 123-456-7890\n```\n## 10. Methods\n\nEncapsulate reusable logic:\n```\n    public class Rectangle\n    {\n        public double Width { get; set; }\n        public double Height { get; set; }\n    \n        public double GetArea()\n        {\n            return Width * Height;\n        }\n    }\n    \n    public class Program\n    {\n        public static void Main(string[] args)\n        {\n            Rectangle rect = new Rectangle();\n            rect.Width = 5;\n            rect.Height = 10;\n    \n            double area = rect.GetArea();\n            Console.WriteLine($\"Area of rectangle: {area}\");\n        }\n    }\n```\n## 11. Classes \u0026 Objects\n\nClasses define blueprints for objects:\n```\n    public class MyClass // Class definition\n    {\n        public string PropertyName { get; set; } // Properties store data\n        public void MethodName() { /*...*/ } // Methods define actions\n    }\n    \n    MyClass obj = new MyClass(); // Object creation\n```\n## 12. Exception Handling\n\nManage runtime errors gracefully:\n```\n    public static int GetNumberInput()\n    {\n      while (true)\n      {\n        try\n        {\n          Console.WriteLine(\"Enter a number: \");\n          string input = Console.ReadLine();\n          return int.Parse(input);\n        }\n        catch (FormatException)\n        {\n          Console.WriteLine(\"Invalid input. Please enter a number.\");\n        }\n      }\n    }\n    \n    public static void Main(string[] args)\n    {\n      int number = GetNumberInput();\n      Console.WriteLine($\"You entered: {number}\");\n    }\n```\n## 13. Delegates, Events \u0026 Lambda\n\nFor event-driven programming and method handling:\n```\n    public delegate void MyDelegate(); // Delegate declaration\n    \n    event MyDelegate MyEvent; // Event declaration\n    \n    public class Person\n    {\n      public string Name { get; set; }\n      public int Age { get; set; }\n    }\n    \n    public static void Main(string[] args)\n    {\n      List\u003cPerson\u003e people = new List\u003cPerson\u003e()\n      {\n        new Person { Name = \"Alice\", Age = 30 },\n        new Person { Name = \"Bob\", Age = 25 },\n        new Person { Name = \"Charlie\", Age = 40 },\n      };\n    \n      people.Sort((p1, p2) =\u003e p1.Name.CompareTo(p2.Name));\n    \n      foreach (var person in people)\n      {\n        Console.WriteLine(person.Name); // Output: Alice, Bob, Charlie (sorted by name)\n      }\n    }\n```\n## 14. LINQ (Language-Integrated Query)\n\nQuery capabilities for data manipulation:\n```\n    using System.Linq;\n    \n    public static void Main(string[] args)\n    {\n      List\u003cint\u003e numbers = new List\u003cint\u003e() { 1, 2, 3, 4, 5, 6 };\n      var evenNumbers = numbers.Where(x =\u003e x % 2 == 0);\n    \n      foreach (var number in evenNumbers)\n      {\n        Console.WriteLine(number); // Output: 2, 4, 6\n      }\n    }\n```\n## 15. Attributes\n\nAdd metadata to code elements:\n```\n    [Obsolete(\"Use the new DoSomethingV2 method instead.\")]\n    public void DoSomething()\n    {\n      // Implementation here\n    }\n    \n    public void DoSomethingV2()\n    {\n      // New and improved implementation\n    }\n```\n## 16. Async/Await\n\nFor non-blocking code execution:\n```\n    using System.Threading.Tasks;\n    \n    public static async Task DownloadFileAsync(string url, string filePath)\n    {\n      // Simulate downloading data asynchronously\n      await Task.Delay(2000); // Simulate a 2-second download\n    \n      // Write downloaded data to the file\n      File.WriteAllText(filePath, \"Downloaded content\");\n      Console.WriteLine($\"File downloaded to: {filePath}\");\n    }\n    \n    public static void Main(string[] args)\n    {\n      string url = \"https://example.com/data.txt\";\n      string filePath = \"downloaded_data.txt\";\n    \n      DownloadFileAsync(url, filePath);\n    \n      // Continue program execution while download happens in the background\n      Console.WriteLine(\"Downloading file...\");\n      Console.WriteLine(\"Meanwhile, you can do other things...\");\n    }\n```\n## 17. Miscellaneous\n\nAdditional language features:\n\n* enum, interface, class, record, struct\n\n* dynamic, is, as, var, nameof\n\n## 18. String Manipulation\n\nPowerful string handling methods:\n```\n    string.Concat(); // Combine strings\n    string.Join(); // Join elements\n    str.Split(); // Split string\n    str.ToUpper(); // Convert to uppercase\n    str.ToLower(); // Convert to lowercase\n```\n## 19. File I/O\n\nOperations with files:\n```\n    using System.IO; // Required for File I/O\n    \n    File.ReadAllText(path); // Read file content\n    File.WriteAllText(path, content); // Write to file\n    File.Exists(path); // Check file existence\n```\n## 20. Date \u0026 Time\n\nDate and time manipulation:\n```\n    using System;\n    \n    public static void Main(string[] args)\n    {\n      DateTime startDate = DateTime.Parse(\"2024-03-10\");\n      DateTime endDate = DateTime.Now;\n    \n      TimeSpan difference = endDate - startDate;\n      Console.WriteLine($\"Time difference: {difference.Days} days, {difference.Hours} hours\");\n    }\n```\n## 21. Generics\n\nType-safe data structures:\n```\n    public class Stack\u003cT\u003e\n    {\n      private List\u003cT\u003e items = new List\u003cT\u003e();\n    \n      public void Push(T item)\n      {\n        items.Add(item);\n      }\n    \n      public T Pop()\n      {\n        T item = items[items.Count - 1];\n        items.RemoveAt(items.Count - 1);\n        return item;\n      }\n    }\n    \n    public static void Main(string[] args)\n    {\n      Stack\u003cstring\u003e messages = new Stack\u003cstring\u003e();\n      messages.Push(\"Hello\");\n      messages.Push(\"World\");\n    \n      string message = messages.Pop();\n      Console.WriteLine(message); // Output: World\n    }\n```\n## 22. Nullables\n\nAllow value types to be null:\n```\n    int? nullableInt = null; // Nullable integer\n```\n## 23. Attributes \u0026 Reflection\n\nMetadata and type introspection:\n```\n    public class Person\n    {\n      public string Name { get; set; }\n      public int Age { get; set; }\n    }\n    \n    public static void Main(string[] args)\n    {\n      Type personType = typeof(Person);\n      PropertyInfo[] properties = personType.GetProperties();\n    \n      foreach (PropertyInfo property in properties)\n      {\n        Console.WriteLine(property.Name); // Output: Name, Age\n      }\n    }\n```\n## 24. Extension Methods\n\nAdd methods to existing types:\n```\n    public static class StringExtensions\n    {\n      public static string ToUppercase(this string str)\n      {\n        return str.ToUpper();\n      }\n    }\n    \n    public static void Main(string[] args)\n    {\n      string message = \"Hello, world!\";\n      string uppercased = message.ToUppercase(); // Using the extension method\n      Console.WriteLine(uppercased); // Output: HELLO, WORLD!\n    }\n```\n## 25. Dependency Injection\n\nLoosely coupled code design:\n```\n    public interface ILogger\n    {\n      void LogMessage(string message);\n    }\n    \n    public class MyService\n    {\n      private readonly ILogger _logger;\n    \n      public MyService(ILogger logger)\n      {\n        _logger = logger;\n      }\n    \n      public void DoSomething()\n      {\n        _logger.LogMessage(\"Doing something...\");\n      }\n    }\n    \n    // Implementing the ILogger interface (example)\n    public class ConsoleLogger : ILogger\n    {\n      public void LogMessage(string message)\n      {\n        Console.WriteLine(message);\n      }\n    }\n    \n    public static void Main(string[] args)\n    {\n      ILogger logger = new ConsoleLogger();\n      MyService service = new MyService(logger);\n      service.DoSomething();\n    }\n```\n## 26. Partial Classes\n\nSplitting a single class definition:\n```\n    public partial class MyClass { /*...*/ } // Partial class definition\n```\n## 27. Interoperability\n\nInterop with other languages:\n```\n    using System;\n    using System.Runtime.InteropServices;\n    \n    [DllImport(\"user32.dll\")]\n    public static extern int MessageBox(IntPtr hWnd, string lpText, string lpCaption, uint uType);\n    \n    public static void Main(string[] args)\n    {\n      MessageBox(IntPtr.Zero, \"Hello from C#!\", \"Interop Example\", 0);\n    }\n```\n## 28. Anonymous Types\n\nCreating unnamed types:csharpCopy code\n```\n    var person = new { Name = \"John\", Age = 30 };\n    Console.WriteLine($\"Name: {person.Name}, Age: {person.Age}\");\n```\n## 29. Tuple\n\nData structures with a specific number of elements:\n```\n    (string Name, int Age) person = (\"Alice\", 30);\n    Console.WriteLine($\"Name: {person.Name}, Age: {person.Age}\"); // Accessing elements using Item1 and Item2\n```\n## 30. Pattern Matching\n\nSimplifies certain programming tasks:\n```\n    object obj = new Person { Name = \"Bob\", Age = 25 };\n    \n    if (obj is Person { Name: \"Bob\", Age \u003e= 18 })\n    {\n      Console.WriteLine(\"Bob is an adult.\");\n    }\n```\n## 31. Local Functions\n\nEncapsulate logic within methods:\n```\n    public static int Calculate(int number)\n    {\n      int Factorial(int n)\n      {\n        if (n == 0) return 1;\n        return n * Factorial(n - 1);\n      }\n    \n      return Factorial(number);\n    }\n    \n    public static void Main(string[] args)\n    {\n      int result = Calculate(5);\n      Console.WriteLine($\"5! = {result}\");\n    }\n```\n## 32. Records\n\nConcise syntax for reference types:\n```\n    public record Person(string Name, int Age);\n    \n    public static void Main(string[] args)\n    {\n      Person person1 = new Person(\"Alice\", 30);\n      Person person2 = new Person(\"Alice\", 30);\n    \n      // Records provide default equality comparison\n      if (person1 == person2)\n      {\n        Console.WriteLine(\"People are equal\");\n      }\n    }\n```\n## 33. with Expressions\n\nNon-destructive mutation for records:\n```\n    var john = new Person(\"John\", 30);\n    var jane = john with { Name = \"Jane\" }; // Non-destructive mutation\n```\n## 34. Indexers and Ranges\n\nFlexible data access:\n```\n    int[] arr = {0, 1, 2, 3, 4, 5};\n    var subset = arr[1..^1]; // Indexer and range usage\n```\n## 35. using Declaration\n\nDispose of IDisposable objects:\n```\n    using var reader = new StreamReader(\"file.txt\"); // using declaration\n```\n## 36. Nullable Reference Types (NRTs)\n\nAvoid null reference exceptions:\n```\n    public class Person\n    {\n      public string Name { get; set; }\n      public int Age { get; set; }\n    }\n    \n    public static void Main(string[] args)\n    {\n      Person person = new Person() { Age = 30 };\n    \n      // NRTs require null checks before accessing properties\n      if (person?.Name != null)\n      {\n        Console.WriteLine(person.Name);\n      }\n      else\n      {\n        Console.WriteLine(\"Name is null\");\n      }\n    }\n```\n## 37. Pattern-Based Using\n\nMore patterns in the using statement:\n```\n    public ref struct ResourceWrapper { /*...*/ } // Resource wrapper\n    \n    using var resource = new ResourceWrapper(); // Pattern-based using\n```\n## 38. Property Patterns\n\nDeconstruct objects in pattern matching:\n```\n    if (obj is Person { Name: \"John\", Age: var age }) { /*...*/ } // Property pattern matching\n```\n## 39. Default Interface Implementations\n\nInterfaces with default method implementations:\n```\n    public interface IPerson { /*...*/ } // Interface with default method\n    public class MyClass : IPerson { /*...*/ } // Class implementing interface\n```\n## 40. Dynamic Binding\n\nRuntime type resolution:\n```\n    dynamic d = 5; // Dynamic binding\n    d = \"Hello\"; // No compile-time type checking\n```\n## Conclusion\n\nThis structured C# Cheat Sheet concludes with advanced topics and techniques, providing a comprehensive reference for developers aiming to enhance their C# programming skills. For detailed examples and further exploration, refer to the specific sections outlined in this guide. Happy coding!\n\n### Clap if you believe in unicorns \u0026 well-structured paragraphs! 🦄📝\n\n### Socials: [C# Publication](https://medium.com/c-sharp-progarmming) | [LinkedIn](https://www.linkedin.com/in/sukhpinder-singh-532284a2/) | [Instagram](https://www.instagram.com/sukhpindersukh/) | [Twitter](https://twitter.com/sukhsukhpinder) | [Dev.to](https://dev.to/ssukhpinder)\n\n![buymeacoffee](https://cdn-images-1.medium.com/max/2000/1*Dpw8-hNGI2fDmosV4E8DVQ.png)\n\n**Inspired By:** [https://zerotomastery.io/cheatsheets/csharp-cheat-sheet/#constants](https://zerotomastery.io/cheatsheets/csharp-cheat-sheet/#constants)\n","funding_links":["https://github.com/sponsors/ssukhpinder","https://buymeacoffee.com/sukhpindersingh","https://medium.com/c-sharp-progarmming"],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fssukhpinder%2Fcsharp-cheatsheet","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fssukhpinder%2Fcsharp-cheatsheet","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fssukhpinder%2Fcsharp-cheatsheet/lists"}