GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing www.tutorialspoint.com — C# Cheatsheet
Selected Reading
C# CheatsheetThe 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
1. Overview of Basic StructureThe 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 CommentsA comment is a part of the program which is ignored by the compiler. In C#, there are three ways to declare the comments −
3. Understanding Data TypesThe data type defines the type of data that is stored. They can be divided into two main groups − I. Value TypeThe value type store the actual data. Following is the list of types that represent variables −
II. Reference TypesReference types store the memory address of element. The list of reference types is as follows − 4. Working with VariablesIn 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 ConstantsIn 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 StatementsThe 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 IterationsThe 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 ArraysAn 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 ListsA 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 DictionariesA 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 MethodsA 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 OverviewThe 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 ExceptionsThe 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 ExpressionsDelegates, 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 AttributesThe 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
[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 AwaitThe 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 ManipulationString 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 −
19. File Input/Output OperationsThis 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 TimeDate 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 GenericsGenerics 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 usageThe 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 ReflectionThe 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 MethodsWhile 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 InjectionDependency 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 ClassesIn 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 −
27. Interoperability FeaturesThe 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 TuplesTuples 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 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 FunctionsThe 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 RecordsA 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 ExpressionsIn 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 OverviewThe 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 DeclarationThe "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 string name = null; // Compiler error because null is not allowed // Nullable Reference Types string? name = null; 37. Pattern-Based "Using" FeaturesThe "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 ImplementationsThe 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 Advertisements
|
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |