C# Cheat Sheet
C# Cheat Sheet
C# Cheat Sheet
C# Introduction
Object-oriented language, with syntax similar to C++ and Java.
Type safe
Component oriented, structured language
Automatic garbage collection
Rich set of libraries
Conditional compilation
Syntax
Case sensitive
Comments are typed within // (single-line) or /**/ (multi-line)
Code is typed inside code blocks {}
Line termination is done using semicolon ;
Supports comment task highlighters like TODO: , NOTE: , WARN: etc…
Variables
<datatype> <variablename> = <initialvalue>;
Variables should start with underscore and cannot contain white spaces.
It can contain numbers but should always start with a capital letter.
It cannot contain any symbols (other than underscore).
Naming Conventions
Class StudentClass
Method GetMarks
Constant Percentile
Data types
Int Integer values like 1234, 10000
https://hackr.io/blog/c-sharp-cheat-sheet#comment-link 1/15
08/07/22, 20:41 Download C# Cheat Sheet PDF for Your Quick Reference
Initialisation of variables
int i = 7;
byte b = 255;
String s = “hackr.io”;
char c = ‘h’;
Constant values
dateVal = str.AsDateTime();
AsDateTime() Convert string into datetime type
IsDateTime() Check if input is date-time
str.isDateTime();
myVal = 1111;
ToString() Convert another data type like int, array, list etc into String
strVal = myVal.ToString();
Operators
Operator Description
https://hackr.io/blog/c-sharp-cheat-sheet#comment-link 2/15
08/07/22, 20:41 Download C# Cheat Sheet PDF for Your Quick Reference
Logical AND
&&
if (isSingle && isMatching)
String Operations
String
Definitions Example
Functions
Compare two strings and returns integer value as output. It returns 0 for true
CompareTo() str2.CompareTo(str1)
and 1 for false.
https://hackr.io/blog/c-sharp-cheat-sheet#comment-link 3/15
08/07/22, 20:41 Download C# Cheat Sheet PDF for Your Quick Reference
EndsWith() checks whether specified character is the last character of string or not. str2.EndsWith(“io”);
compares two string and returns Boolean value true as output if they are
Equals() str2.Equals(str1)
equal, false if not
IndexOf() Returns the index position of first occurrence of specified character. str1.IndexOf(“:”)
ToLower() Converts String into lower case based on rules of the current culture. str1.ToLower();
ToUpper() Converts String into Upper case based on rules of the current culture. str1.ToUpper();
str1.Insert(0, “Welcome”);
Insert() Insert the string or character in the string at the specified position.
str1.Insert(i, “Thank You”);
LastIndexOf() Returns the index position of last occurrence of specified character. str1.LastIndexOf(“T”);
Remove() deletes all the characters from beginning to specified index position. str1.Remove(i);
StartsWith() Checks whether the first character of string is same as specified character. str1.StartsWith(“H”)
Trim() It removes extra whitespaces from beginning and ending of string. str1.Trim();
Modifiers
public field or function accessible by any other code in the same assembly or another assembly that references it
protected Only accessible by code in the same class or struct or a derived class
internal Accessible by any code in the same assembly, but not from another assembly
https://hackr.io/blog/c-sharp-cheat-sheet#comment-link 4/15
08/07/22, 20:41 Download C# Cheat Sheet PDF for Your Quick Reference
protected
Accessible by any code in the same assembly, or by any derived class in another assembly
internal
abstract to indicate a class that is intended only to be a base class of other classes (has to be extended by other classes)
async Indicates that the modified method, lambda expression, or anonymous method is asynchronous
const Specifies that the value of the field or the local variable cannot be modified (constant)
override Provides a new implementation of a virtual member inherited from a base class
partial Defines partial classes, structs, and methods throughout the same assembly
read-only Declares a field that can only be assigned values as part of the declaration or in a constructor in the same class
Declares a member that belongs to the type itself instead of to a specific object, e.g., for static class or method, no object
static
needs to be created
virtual Declares a method or an accessor whose implementation can be changed by an overriding member in a derived class
Indicates that a field can be modified in the program by something such as the operating system, the hardware, or a
volatile
concurrently executing thread
Date/Time formatting
DateTime dt = new DateTime(); gives output as –
dt = new DateTime(yyyy, MM, dd); gives the specified date in yyyy-MM-dd format. Time will be 00:00:00
DateTime.Now.ToShortDateString() prints only the date part by completely omitting the time part
prints the whole date and time based on region, month is printed in letters (JAN, FEB etc.. ) rather
DateTime.Now.ToLongDateString()
than number (01, 02)
https://hackr.io/blog/c-sharp-cheat-sheet#comment-link 5/15
08/07/22, 20:41 Download C# Cheat Sheet PDF for Your Quick Reference
Format
Name Description
specifier
Full date/time
f pattern (short Represents a combination of the long date (D) and short time (t) patterns, separated by a space.
time)
General
date/time
g Represents a combination of the short date (d) and short time (t) patterns, separated by a space.
pattern (short
time)
General
date/time
G Represents a combination of the short date (d) and long time (T) patterns, separated by a space.
pattern (long
time)
Represents a custom DateTime format string using a pattern that preserves time zone information. The
pattern is designed to round-trip DateTime formats, including the Kind property, in text. Then the formatted
Round-trip string can be parsed back using Parse or ParseExact with the correct Kind property value.
o date/time
The custom format string is "yyyy'-'MM'-'dd'T'HH':' mm': 'ss.fffffffK."
pattern
The pattern for this specifier is a defined standard. Therefore, it is always the same, regardless of the culture
used or the format provider supplied.
Formatting does not modify the value of the DateTime object that is being formatted. Therefore, the
application must convert the value to Coordinated Universal Time (UTC) before using this format specifier.
https://hackr.io/blog/c-sharp-cheat-sheet#comment-link 6/15
08/07/22, 20:41 Download C# Cheat Sheet PDF for Your Quick Reference
Custom patterns
–
Any
other (Unknown
An unknown specifier throws a runtime format exception.
single specifier)
character
Arrays
For creating, modifying, sorting and searching arrays.
arrVal.IsFixedSize;
IsSynchronized Checks whether access to the Array is synchronized (thread safe). arrVal.IsSynchronized;
https://hackr.io/blog/c-sharp-cheat-sheet#comment-link 7/15
08/07/22, 20:41 Download C# Cheat Sheet PDF for Your Quick Reference
Length Gets the total number of elements in all the dimensions of the Array. arrVal.Length;
Gets the rank (number of dimensions) of the Array. For example, a one-
Rank arrVal.Rank;
dimensional array returns 1, a two-dimensional array returns 2, and so on.
Array.BinarySearch(arrVal, obj);
Searches a value in a one-dimensional sorted array using a binary
BinarySearch() where obj is the object to be
search algorithm.
searched.
Array.Clear(arrVal, 0, 2);
Clear() Sets a range of elements in an array to the default value of each element type. If arrVal is an array of integers, the
elements at position 0 to 2 will be
set to zero after doing Clear().
Array.ConstrainedCopy(srcArr, 0,
destArr, 3, 5);
conArr = Array.ConvertAll(arrVal,
ConvertAll() Converts an array of one data type to an array of another data type. new Converter<dtype1, dtype2>
(method));
Copies all the elements of the current one-dimensional array to the specified Array.CopyTo(destArr, 4);
CopyTo()
one-dimensional array. copy starts from index 4
Array.CreateInstance(typeof(String),
CreateInstance() Initializes a new instance of the Array class.
length);
Equals() Determines whether the specified object is equal to the current object. arrVal.Equals(arrVal2);
Determines whether the specified array contains elements that match the Array.Exists(srcArr,
Exists()
conditions defined by the specified predicate. “<elementname>”);
Searches for an element that matches the conditions defined by the specified Array.Find(arrVal, <matching
Find()
predicate, and returns the first occurrence within the entire Array. pattern>);
https://hackr.io/blog/c-sharp-cheat-sheet#comment-link 8/15
08/07/22, 20:41 Download C# Cheat Sheet PDF for Your Quick Reference
Retrieves all the elements that match the conditions defined by the specified Array.FindAll(arrVal, <matching
FindAll()
predicate. pattern>);
Searches for an element that matches the conditions defined by the specified Array.FindLast(arrVal, <matching
FindLast()
predicate, and returns the last occurrence within the entire Array. pattern>);
ForEach() Loops through each element of the array and performs the specified action Array.ForEach(arrVal, Action)
Gets a 32-bit integer that represents the number of elements in the specified arrVal.GetLength(i) where i is an
GetLength()
dimension of the Array. integer
Gets a 64-bit integer that represents the number of elements in the specified arrVal.GetLongLength(i) where i is
GetLongLength()
dimension of the Array. an integer
arrVal.GetLowerBound(i) where i is
GetLowerBound() Gets the index of the first element of the specified dimension in the array.
an integer
arrVal.GetUpperBound(i) where i is
GetUpperBound() Gets the index of the last element of the specified dimension in the array.
an integer
GetValue() Gets the value of the specified element in the current Array.
Searches for the specified object and returns the index of its first occurrence in
IndexOf() arrVal.IndexOf(object)
a one-dimensional array or in a range of elements in the array.
SetValue() Sets the specified element in the current Array to the specified value. Array.SetValue(arrVal[i])
https://hackr.io/blog/c-sharp-cheat-sheet#comment-link 9/15
08/07/22, 20:41 Download C# Cheat Sheet PDF for Your Quick Reference
Determines whether every element in the array matches the conditions defined Array.TrueForAll(arrVal, <matching
TrueForAll()
by the specified predicate. pattern>)
Control Statements
if (true) {...}
else {...}
switch (var)
case 1: break;
switch
case 2: break;
default: break;
do {...}
do... while
while (true);
try {...}
catch {...}
finally {...}
Regular Expressions
+ match one or more occurrence
? match 0 or 1 occurrence
a|b either a or b
\n new line
\r carriage return
https://hackr.io/blog/c-sharp-cheat-sheet#comment-link 10/15
08/07/22, 20:41 Download C# Cheat Sheet PDF for Your Quick Reference
\t tab
Collections
Arraylist
Capacity Gets or sets the number of elements that the ArrayList can contain.
IsFixedSize Gets a value indicating whether the ArrayList has a fixed size.
AddRange(ICollection c); Adds the elements of an ICollection to the end of the ArrayList.
GetRange(int index, int count); Returns an ArrayList which represents a subset of the elements in the source ArrayList.
IndexOf(object); Returns the zero-based index of the first occurrence of a value in the ArrayList or in a portion of it.
Insert(int index, object value); Inserts an element into the ArrayList at the specified index.
InsertRange(int index, ICollection c); Inserts the elements of a collection into the ArrayList at the specified index.
Remove(object obj); Removes the first occurrence of a specific object from the ArrayList.
RemoveAt(int index); Removes the element at the specified index of the ArrayList.
RemoveRange(int index, int count); Removes a range of elements from the ArrayList
SetRange(int index, ICollection c); Copies the elements of a collection over a range of elements in the ArrayList.
TrimToSize(); Sets the capacity to the actual number of elements in the ArrayList.
Hashtable
IsFixedSize Gets a value indicating whether the Hashtable has a fixed size
Item Gets or sets the value associated with the specified key.
https://hackr.io/blog/c-sharp-cheat-sheet#comment-link 11/15
08/07/22, 20:41 Download C# Cheat Sheet PDF for Your Quick Reference
Add(object key, object value); Adds an element with the specified key and value into the Hashtable
Remove(object key); Removes the element with the specified key from the Hashtable.
SortedList
Item Gets and sets the value associated with a specific key in the SortedList.
Add(object key, object value) Adds an element with the specified key and value into the SortedList.
GetByIndex(int index); Gets the value at the specified index of the SortedList.
GetKey(int index); Gets the key at the specified index of the SortedList.
IndexOfKey(object key); Returns the zero-based index of the specified key in the SortedList.
IndexOfValue(object value); Returns the zero-based index of the first occurrence of the specified value in the SortedList.
Remove(object key); Removes the element with the specified key from the SortedList.
TrimToSize(); Sets the capacity to the actual number of elements in the SortedList.
Stack
https://hackr.io/blog/c-sharp-cheat-sheet#comment-link 12/15
08/07/22, 20:41 Download C# Cheat Sheet PDF for Your Quick Reference
Peek(); Returns the object at the top of the Stack without removing it.
Pop(); Removes and returns the object at the top of the Stack.
Queue
Dequeue(); Removes and returns the object at the beginning of the Queue.
TrimToSize(); Sets the capacity to the actual number of elements in the Queue.
Dictionary
Item Gets or sets the element with the specified key in the Dictionary<TKey,TValue>.
Remove Removes the first occurrence of specified item from the Dictionary<TKey, TValue>.
TryGetValue Returns true and assigns the value with specified key, if key does not exists then return false.
Exception Handling
try{
throw;
https://hackr.io/blog/c-sharp-cheat-sheet#comment-link 13/15
08/07/22, 20:41 Download C# Cheat Sheet PDF for Your Quick Reference
Methods
static method, no object needed to call method public static void MyMethod(){}
Classes
Class MyClass
/*Class definition*/
Object creation –
Partial Class
Classes within the same namespace can be split into smaller classes with same name.
00:00/01:36
// PartialClass1.cs // PartialClass2.cs
{ {
{ {
{ {
} }
} }
} }
https://hackr.io/blog/c-sharp-cheat-sheet#comment-link 14/15
08/07/22, 20:41 Download C# Cheat Sheet PDF for Your Quick Reference
pc.HelloWorld();
pc.HelloUser();
File Handling
File.Exists Check the existence of the file in the specified path File.Exists(path)
File.ReadAllLines(path)
File.ReadAllLines Read all the lines from the file specified by the path Console.WriteLines(File.ReadAllLines(path)
// Write to console
File.ReadAllText Read all the text from the file and store it as a single string File.ReadAllText(path)
https://hackr.io/blog/c-sharp-cheat-sheet#comment-link 15/15