
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Arithmetic Operators
- C# - Assignment Operators
- C# - Relational Operators
- C# - Logical Operators
- C# - Bitwise Operators
- C# - Miscellaneous Operators
- C# - Operators Precedence
- C# Conditional Statements
- C# - Decision Making
- C# - If
- C# - If Else
- C# - Nested If
- C# - Switch
- C# - Nested Switch
- C# Control Statements
- C# - Loops
- C# - For Loop
- C# - While Loop
- C# - Do While Loop
- C# - Nested Loops
- C# - Break
- C# - Continue
- C# OOP & Data Handling
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
C# Cheatsheet
The C# cheatsheet provides a quick reference to all the fundamental concepts. C# is popular for backend programming and is used in web applications, desktop applications, OOP, and cross-platform development with .NET, offering strong job opportunities. By studying this cheat sheet, one can effectively prepare for interviews and exams. Go through this cheat sheet and learn the C# programming language.
Table of Content
- Overview of Basic Structure
- Types of Comments
- Understanding Data Types
- Working with Variables
- Using Constants
- Exploring Conditional Statements
- Loops and Iterations
- Working with Arrays
- Introduction to Lists
- Understanding Dictionaries
- Defining Methods
- Classes & Objects Overview
- Handling Exceptions
- Delegates, Events, & Lambda Expressions
- Introduction to LINQ (Language−Integrated Query)
- Working with Attributes
- Using Async and Await
- String Operations and Manipulation
- File Input/Output Operations
- Working with Date and Time
- Understanding Generics
- Nullables and their Usage
- Attributes and Reflection
- Creating Extension Methods
- Implementing Dependency Injection
- Using Partial Classes
- Interoperability Features
- Anonymous Types in C#
- Working with Tuples
- Pattern Matching in C#
- Using Local Functions
- Introduction to Records
- Using with Expressions
- Indexers and Ranges Overview
- Understanding using Declaration
- Nullable Reference Types (NRTs)
- Pattern-Based Features
- Default Interface Implementations
- Dynamic Binding in C#
1. Overview of Basic Structure
The basic structure of C# represents the foundation of the programming language. This file contains the main method by which the program starts executing. Below is the basic structure of C# −
using System; class Program { static void Main() { Console.WriteLine("Hello, World!"); } }
2. Types of Comments
A comment is a part of the program which is ignored by the compiler. In C#, there are three ways to declare the comments −
- Single line comment (//): This comment is the single line of code.
- Multi line comment (/* ... */): This comment the multiple lines of code.
- XML document comment (///): This is used to provide documentation for methods, classes, or properties.
3. Understanding Data Types
The data type defines the type of data that is stored. They can be divided into two main groups −
I. Value Type
The value type store the actual data. Following is the list of types that represent variables −
- Integral Type(int, long, short, byte, sbyte, uint, ulong, ushort)
- Floating-Point Type(float, double, decimal)
- Boolean Type(bool)
- Character Type(char)
- Structure(Struct)
II. Reference Types
Reference types store the memory address of element. The list of reference types is as follows −
4. Working with Variables
In programming, variables can store the memory location by holding values. The value stored in the variable can change the execution of the program. Thus, variables allow users to store, modify, and retrieve data.
int num = 5; // integer string word = "Hello"; // string
5. Using Constants
In C#, constants are immutable values that are known at compile time and do not change during the execution of a program.
const int ConstNum = 21; // The value of contants always remain same.
Note that constants of C# follow the PascalCase style which means it starts with an uppercase letter.
6. Exploring Conditional Statements
The conditional statements of C# are used to control the flow of the program. It executes different blocks of code based on specific conditions.
// To check the first condition if (condition) { /*...*/ } // To check additional conditions if the previous one fail else if (condition) { /*...*/ } // The else block executed if none of the above conditions are true else { /*...*/ } // Switch statement to compare a single variable with multiple values switch (variable) { case val_1: // Code for val_1 break; default: // Default block executed if no cases match break; }
7. Loops and Iterations
The loop performs the repetitive task on the certain condition where an iterator is used to indicate the element position from the given list of elements.
for (int i = 0; i < 5; i++) { /*...*/ } foreach (var item in collection) { /*...*/ } while (condition) { /*...*/ } do { /*...*/ } while (condition);
8. Working with Arrays
An array is referred by a fixed number of elements of the same type in a contiguous block of memory.
// Array with 5 elements int[] n = new int[5]; // Assign the array values n[0] = 11; n[1] = 12; n[2] = 13;
9. Introduction to Lists
A list is a dynamic collection that stores a variable number of elements of the same type.
// package for list using System.Collections.Generic; class Program { static void Main() { // list from the package List<int> num = new List<int>(); // add the element 10 to the list num.Add(10) // remove the element present at index 3 num.Remove(3) // check the element if it is present or not num.contain(6) } }
10. Understanding Dictionaries
A dictionary is a collection of data that is stored in the form of key-value pairs, where each key is unique.
// Create a dictionary with string keys and int values Dictionary<string, int> ages = new Dictionary<string, int>(); // Add key-value pairs to the dictionary ages["Vivek"] = 25; ages["Salman"] = 20; ages["Arjun"] = 25;
11. Defining Methods
A method is a block of code that performs specific tasks. This is encapsulated logic for reusing code.
public static int SubNum(int n1, int n2) { // return the subtraction return n1 - n2; }
12. Classes and Objects Overview
The classes refer to the structure of an object that shows properties and methods. An object is an instance of a class; it can be created using the new keyword.
Class Definition
class ClassName { // Fields (Properties) public dataType fieldName; // Constructor public ClassName(parameters) { // Initialization } // Methods public returnType MethodName() { // Method code } }
Creating an Object
ClassName objectName = new ClassName(parameters);
13. Handling Exceptions
The exception handling allows the user to handle the run-time error rather than the program crashing. The C# exception handling is built upon four keywords: try, catch, finally, and throw.
try { // the code may cause an exception int result = 40 / 0; // Division by zero } catch (DivideByZeroException ex) { // this handle the exception Console.WriteLine("Error: " + ex.Message); } finally { // this block will always execute Console.WriteLine("This will always run."); }
14. Delegates, Events, and Lambda Expressions
Delegates, events, and lambda expressions in C# are part of event-driven applications and allow for easier code maintenance.
using System; // Delegate definition public delegate void MyDelegate(); // Event declaration event MyDelegate MyEvent; // Lambda expression with Func for addition of two integers Func<int, int, int> add = (a, b) => a + b; class Program { static void Main(string[] args) { // Subscribing to the event MyEvent += () => Console.WriteLine("Event triggered!"); // Triggering the event MyEvent?.Invoke(); // Using the lambda expression (Func) to add two numbers int result = add(5, 3); Console.WriteLine($"The result of adding 5 and 3 is: {result}"); } }
15. Introduction to LINQ (Language-Integrated Query)
The LINQ is a feature in C# that allows users to generate the query and data manipulation from multiple sources. Its syntax is similar to SQL.
using System.Linq; class Program { static void Main() { var data = new[] // LINQ query var query = from item in data where /* condition */ select element; } }
16. Working with Attributes
The attribute provides a piece of additional information in the program. This can be used during the runtime. Below is the list of attributes to work on C# programs −
- Defining an Attribute: Create a class that inherits from System.Attribute.
- Applying an Attribute: We can use square brackets[] to apply attributes for classes, methods, or, properties.
- Predefined Attributes: C# has built-in attributes like [Obsolete] and [Serializable].
// Defining an attribute [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class MyCustomAttribute : Attribute { ... } // Applying an attribute [MyCustomAttribute("This is a custom attribute")] public class MyClass { [MyCustomAttribute("This is a method attribute")] public void MyMethod() { } } // Pre-defined attribute [Obsolete("Use NewMethod instead")] public void OldMethod() { }
17. Using Async and Await
The async and await keywords in C# make it easy to write code that runs in the background, keeping the program responsive while tasks are executed. This approach pauses a task until it completes, such as waiting for a file to load, and then continues smoothly.
// Asynchronous method to read the file public static async Task<string> ReadFileAsync(string filePath) { // Call the asynchronous method return await reader.ReadToEndAsync(); }
18. String Operations and Manipulation
String manipulation is the process of changing textual data to achieve the desired result. C# has a rich set of built-in methods through the string class. Some of the common string manipulation operations are −
- string.Concat() − This concatenates two strings.
- string.Substring() − This extracts the portion of the string.
- string.Length() − This returns the number of characters present in the string.
- string.Replace() − This method replaces the substring instead of the string.
- string.ToUpper() − This converts the string into uppercase.
- string.ToLower() − This converts the string into lowercase.
- string.Trim() − This removes the whitespace characters.
- string.Indexof() − This finds the index of the first occurrence of the string.
- string.Contain() − This checks the existance of string.
- string.StartsWith()/string.EndsWith() − This checks if the string starts or ends with a specific substring.
- \n or \t − This is an escape sequence character. \n represents the newline character, whereas \t is for tab space..
19. File Input/Output Operations
This is the basic communication process to manage the file in a disk. The input and output refer to reading and writing in files.
// Read the text from the file file.ReadAllText("file_eg.txt"); // Write text in a file file.WriteAllText("file_eg.txt", "This is Tutorialspoint!"); // Add the text to a file file.AppendAllText("file_eg.txt", "\nAppend the text"); // Check the existance of file file.Exists()
20. Working with Date and Time
Date and time play an important role in developing applications that support business decisions and processes. Here, we briefly describe the usage of date and time code.
// get the current date and time // Local time DateTime currentDateTime = DateTime.Now; // UTC time DateTime utcDateTime = DateTime.UtcNow; // get the date and time using the class DateTime now = DateTime.Now; DateTime today = DateTime.Today;
21. Understanding Generics
Generics are defined with a type parameter that allows the user to create a class with a placeholder for the data type.
public class Box<T> { public T Value { get; set; } public Box(T value) { Value = value; } }
22. Nullables and their usage
The Nullables is one of the parts of the value type that directly declare the value. To declare a nullable type, use the "?" symbol after the value type. Below is the representation −>
// Nullable integer int? myNullableInt = null; // Nullable double double? myNullableDouble = 3.14; // Nullable boolean bool? myNullableBool = null;
23. Attributes and Reflection
The attribute discusses the metadata of the program elements, while reflection allows the user to inspect and interact with the metadata during runtime to manipulate queries or types such as types, methods, and other elements.
// Custom attribute applied to a class. [CustomAttribute] public class MyEmp { // do something } // Use reflection to get the attribute: Attribute[] attrs = Attribute.GetCustomAttributes(typeof(MyEmp));
24. Creating Extension Methods
While creating an extension method, add new methods to existing types such as classes, struct, or interfaces without any changes to the source code. This is defined under static classes and must declare "static" and "this" keywords to identify the type it uses for the first parameter. Here, we are illustrating the example on string reverse.
public static class StringExtensions { // Extension method public static string ReverseString(this string str) { char[] charArray = str.ToCharArray(); Array.Reverse(charArray); return new string(charArray); } }
25. Implementing Dependency Injection
Dependency injection is a design pattern for software development applications that follow the OOps technique. In this pattern, a class receives its dependencies from an external source instead of creating them internally.
In this example, Client depends on IService, i.e. injected through its constructor.
public interface IService { void Execute(); } public class Service : IService { public void Execute() => Console.WriteLine("Service Executed"); } public class Client { private readonly IService _service; public Client(IService service) { _service = service; } public void Run() => _service.Execute(); } var service = new Service(); var client = new Client(service); client.Run();
26. Using Partial Classes
In C#, partial class allows the user to split the class definition, struct, or interface into multiple files. This is useful when the user wants to work with larger classes or files.
First File − student_one.cs
public partial class Stu { public string Name { get; set; } }
Second File − student_two.cs
public partial class Stu { public int Age { get; set; } public void DisplayInfo() { Console.WriteLine($"Name: {Name}, Age: {Age}"); } }
Points to remember −
- Above two files contain the definition of same class Stu.
- The partial keyword represent the class definition which is distributed across multiple files.
27. Interoperability Features
The interoperability features of C# allow users to set multiple programming languages within the same system.
28. Anonymous Types in C#
While creating an anonymous type, use the keyword "new" that specify the properties and the values to the object initializers.
var student = new { Name = "Tapas", Age = 25 }; Console.WriteLine(person.Name); // result - Tapas Console.WriteLine(person.Age); // result - 25
29. Working with Tuples
Tuples are a data structure that allows users to store multiple values of different types within a single object.
var tuple = (5, "Tutorialspoint", 32.9);
Note: C# tuples introduced in C# 7.0 and higher version.
30. Pattern Matching in C#
The pattern matching allows the user to check the object based on specific type, value, or structure. The following is the list of patterns that are used in C# as follows −
- Type Patterns: This match object's type.
- Property Patterns: This match the values of properties or fields within an object.
- Constant Patterns: This can match against specific constants.
- Relational Patterns: This type of pattern is based upon comparison operators.
- Logical Patterns: It combine multiple patterns using logical operators.
// Type Pattern object n1 = 42; if (obj is int n1) { Console.WriteLine($"Integer: {n1}"); } // Property pattern var person = new { Name = "Mary", Age = 30 }; if (person is { Name: "Mary", Age: > 25 }) { Console.WriteLine("This is Mary and she is older than 25."); } // Constant Pattern int n = 25; switch (n) { case 0: Console.WriteLine("One"); break; case 10: Console.WriteLine("Eight"); break; default: Console.WriteLine("Other"); break; } // Relational Pattern int age = 20; if (age is >= 18 and <= 65) { Console.WriteLine("You are an adult."); } // Logical Pattern(and, or, and not) int value = 15; if (value is > 10 and > 20) { Console.WriteLine("The value is ranges between 10 and 20."); }
31. Using Local Functions
The local function is a function defined inside a method and is used only within its scope.
static void Main() { // Local function definition int sub(int a, int b) { return a - b; } // Call the local function int result = sub(10, 5); }
32. Introduction to Records
A record is an immutable data model that has been introduced in C# 9.0. Its main purpose is to store and compare data instead of modifying it.
public record record_name(string Name, int Age, ...);
33. Using with Expressions
In C#, the "with" expression is used to create a new object by copying an existing object and modifying specific properties.
var New_object = Existing_object with { property_name = new_value };
34. Indexers and Ranges Overview
The indexers are similar to array that enables collection of element in a sequential form.
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // access the element index between 2 and 4(eg. of ranges) var range = numbers[2..5]; // get the element from index 0 to 3 var range2 = numbers[..4];
35. Understanding using Declaration
The "using" declaration of C# is the resources like file or stream. This declaration ensures the resource is closed and ready to reuse after the program is done with it.
// The file is automatically closed in the end of the scope. using var file = new FileStream("file_example.txt", FileMode.Open);
36. Nullable Reference Types (NRTs)
There are two ways to identify NRTs −
- Non-Nullable Reference Types: By default, reference types cannot be null.
- Nullable Reference Types: It simply use ? syntax after the type like string?.
// Non-Nullable Reference Types string name = null; // Compiler error because null is not allowed // Nullable Reference Types string? name = null;
37. Pattern-Based "Using" Features
The "using statement" in C# ensures the proper disposal of objects that implement the IDisposable interface, either synchronously or asynchronously. We can relate these features to the file handling process.
using (FileStream fileStream = new FileStream(path)) { // do something }
38. Default Interface Implementations
The feature of default interface allows users to add new methods to interfaces without breaking the existing implementation. Below is the representation −
public interface IExample { // Implementation of default interface void SayHello() { Console.WriteLine("Hello from the default interface implementation!"); } }
39. Dynamic Binding in C#
In C#, dynamic binding is the process of resolving method calls, properties, or operations at runtime instead of compile time. This feature is achieved using dynamic. In simple, we can say type checking during runtime.
dynamic ob = "Hello" // This is resolved at runtime Console.WriteLine(ob.Length); // Throw an error at runtime because integer don't have the property of Length ob = 23