0% found this document useful (0 votes)
12 views

C# Cheat Sheet

This document provides an overview of C# syntax, variables, data types, operators, and string operations. It covers key concepts like object-oriented programming, type safety, and garbage collection in C#. The document also includes examples of declaring variables, initializing values, and performing operations on different data types.

Uploaded by

korismith
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

C# Cheat Sheet

This document provides an overview of C# syntax, variables, data types, operators, and string operations. It covers key concepts like object-oriented programming, type safety, and garbage collection in C#. The document also includes examples of declaring variables, initializing values, and performing operations on different data types.

Uploaded by

korismith
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

8/24/22, 12:13 PM Download C# Cheat Sheet PDF for Your Quick Reference

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

Local variable firstName

Private variable avgMarks

Constant Percentile

Data types

https://hackr.io/blog/c-sharp-cheat-sheet 1/24
8/24/22, 12:13 PM Download C# Cheat Sheet PDF for Your Quick Reference

Int Integer values like 1234, 10000

Double 64-bit floating-point, 3.145644

Float Floating point number, 3.1454

String Set of characters, “Welcome.”

Byte 8bit unsigned integer

Char 16 bit Unicode character, ‘A.’

Long 64 bit signed integer, -9.0789

Decimal High precision decimal numbers

Bool True or false Boolean value

Enums Value data type contains its value

Struct value type that is used to represent a record

Initialisation of variables

int i = 7;
byte b = 255;
String s = “hackr.io”;
char c = ‘h’;

Constant values

const String lastDayOfWeek = “Friday”;

String Data type conversion


Method Description Example

https://hackr.io/blog/c-sharp-cheat-sheet 2/24
8/24/22, 12:13 PM Download C# Cheat Sheet PDF for Your Quick Reference

AsInt(), Convert string into integer intVal = str.AsInt();


IsInt() Check If the input is int str.IsInt()

AsFloat(), Convert string into float floatVal = str.AsFloat();

IsFloat() Check if the input is float str.IsFloat()

AsDecimal() Convert string into decimal decVal = str.AsDecimal();

IsDecimal() Check if input is decimal str.IsDecimal()

dateVal =
AsDateTime() Convert string into datetime type str.AsDateTime();

IsDateTime() Check if input is date-time


str.isDateTime();

AsBool() Convert string into Boolean boolVal = str.AsBool();


IsBool() Check if input is Boolean str.IsBool();

Convert another data type like int, array, list etc into myVal = 1111;
ToString()
String strVal = myVal.ToString();

Operators
Operator Description

= Assigns variable value. (i = 10)

+ Adds a value or variable. (i + j) or (i + 3)

- Subtracts values or variables. (i – j)

* Multiplies values or variables. (i*j)

/ Divides values or variables. (i/j)

+= Increments a variable. ( i+=1)

https://hackr.io/blog/c-sharp-cheat-sheet 3/24
8/24/22, 12:13 PM Download C# Cheat Sheet PDF for Your Quick Reference

-= Decrements a variable. (i-=1)

== Equality. Returns true if values are equal. (i==10)

!= Inequality. Returns true if values are not equal. (I != 10)

< Less Than (i < 5)

> Greater Than (i > 5)

<= Less Than or Equal to (i <= 5)

>= Greater than equal to (i >= 5)

+ String concatenation (“Welcome to ” + websiteName)

Call methods, constant variables etc..


.
arrVal.ToString()

Calculations, passing parameters etc…


()
(i+10)*(i-10); multiply(i, j)

[] Access values in arrays or collections. name[i]

Reversing Boolean value


!
if (!isMatching)

Logical AND
&&
if (isSingle && isMatching)

sizeof() returns the size of a data type

typeof() returns the type of object – string, integer etc…

String Operations

https://hackr.io/blog/c-sharp-cheat-sheet 4/24
8/24/22, 12:13 PM Download C# Cheat Sheet PDF for Your Quick Reference

String
Definitions Example
Functions

Clone() Make clone of string. str2 = str1.Clone()

Compare two strings and returns integer value as


CompareTo() str2.CompareTo(str1)
output. It returns 0 for true and 1 for false.

checks whether specified character or string is


Contains() str2.Contains(“hack”);
exists or not in the string value.

checks whether specified character is the last


EndsWith() str2.EndsWith(“io”);
character of string or not.

compares two string and returns Boolean value true


Equals() str2.Equals(str1)
as output if they are equal, false if not

GetHashCode() returns HashValue of specified string. str1.GetHashCode()

GetType() returns the System.Type of current instance. str1.GetType()

returns the Stystem.TypeCode for class


GetTypeCode() str1.GetTypeCode()
System.String.

Returns the index position of first occurrence of


IndexOf() str1.IndexOf(“:”)
specified character.

Converts String into lower case based on rules of


ToLower() str1.ToLower();
the current culture.

Converts String into Upper case based on rules of


ToUpper() str1.ToUpper();
the current culture.

Insert the string or character in the string at the str1.Insert(0, “Welcome”);


Insert()
specified position. str1.Insert(i, “Thank You”);

Check whether this string is in Unicode


IsNormalized() str1.IsNormalized()
normalization form

https://hackr.io/blog/c-sharp-cheat-sheet 5/24
8/24/22, 12:13 PM Download C# Cheat Sheet PDF for Your Quick Reference

Returns the index position of last occurrence of


LastIndexOf() str1.LastIndexOf(“T”);
specified character.

Length returns length of string. str1.Length;

deletes all the characters from beginning to


Remove() str1.Remove(i);
specified index position.

Replace() replaces the specified character with another str1.Replace(‘a’, ‘e’);

str1 = “Good morning and


Welcome”;
This method splits the string based on specified
Split() String sep = {“and”};
value.
strArray = str1.Split(sep,
StringSplitOptions.None);

Checks whether the first character of string is same


StartsWith() str1.StartsWith(“H”)
as specified character.

Substring() This method returns substring. str1.Substring(1, 7);

ToCharArray() Converts string into char array. str1.ToCharArray()

It removes extra whitespaces from beginning and


Trim() str1.Trim();
ending of string.

Modifiers
field or function accessible by any other code in the same assembly or another
public
assembly that references it

private Only available by code in the same class or struct

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 6/24
8/24/22, 12:13 PM 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
internal assembly

to indicate a class that is intended only to be a base class of other classes (has to be
abstract
extended by other classes)

Indicates that the modified method, lambda expression, or anonymous method is


async
asynchronous

const Specifies that the value of the field or the local variable cannot be modified (constant)

event Declares an event

extern Indicates that the method is implemented externally

new Explicitly hides a member inherited from a base class

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

Declares a field that can only be assigned values as part of the declaration or in a
read-only
constructor in the same class

sealed Specifies that a class cannot be inherited

Declares a member that belongs to the type itself instead of to a specific object, e.g., for
static
static class or method, no object needs to be created

unsafe Declares an unsafe context

Declares a method or an accessor whose implementation can be changed by an


virtual
overriding member in a derived class

Indicates that a field can be modified in the program by something such as the operating
volatile
system, the hardware, or a concurrently executing thread

Date/Time formatting

https://hackr.io/blog/c-sharp-cheat-sheet 7/24
8/24/22, 12:13 PM Download C# Cheat Sheet PDF for Your Quick Reference

DateTime dt = new DateTime(); gives output as –

dt.ToString(); 01-01-0001 00:00:00

dt = DateTime.Now; gives current date and time

gives the specified date in yyyy-MM-dd format. Time will be


dt = new DateTime(yyyy, MM, dd);
00:00:00

dt = new DateTime(yyyy, MM, dd,


gives specified date and time in the 24-hour format
hh, min, ss);

dt = new DateTime(yyyy, MM, dd,


hh, mm, ss); gives only the date, with the time part set to 00:00:00
dt1 = dt.Date;

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


DateTime.Now.ToLongDateString()
printed in letters (JAN, FEB etc.. ) rather than number (01, 02)

DateTime format specifiers


Format
Name Description
specifier

Represents a custom DateTime format string defined by the


Short date current ShortDatePattern property.
d
pattern For example, the custom format string for the invariant culture is
"MM/dd/yyyy."

Represents a custom DateTime format string defined by the


Long date current LongDatePattern property.
D
pattern For example, the custom format string for the invariant culture is "dddd,
dd MMMM yyyy."

https://hackr.io/blog/c-sharp-cheat-sheet 8/24
8/24/22, 12:13 PM Download C# Cheat Sheet PDF for Your Quick Reference

Full date/time
Represents a combination of the long date (D) and short time (t)
f pattern (short
patterns, separated by a space.
time)

Represents a custom DateTime format string defined by the


Full date/time current FullDateTimePattern property.
F pattern (long
time) For example, the custom format string for the invariant culture is "dddd,
dd MMMM yyyy HH:mm: ss."

General
date/time Represents a combination of the short date (d) and short time (t)
g
pattern (short patterns, separated by a space.
time)

General
date/time Represents a combination of the short date (d) and long time (T)
G
pattern (long patterns, separated by a space.
time)

Represents a custom DateTime format string defined by the


Month day current MonthDayPattern property.
M or m
pattern For example, the custom format string for the invariant culture is
"MMMM dd."

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
Round-trip formatted string can be parsed back using Parse or ParseExact with the
o date/time correct Kind property value.
pattern
The custom format string is "yyyy'-'MM'-'dd'T'HH':' mm': 'ss.fffffffK."

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.

https://hackr.io/blog/c-sharp-cheat-sheet 9/24
8/24/22, 12:13 PM Download C# Cheat Sheet PDF for Your Quick Reference

Represents a custom DateTime format string defined by the


current RFC1123Pattern property. The pattern is a defined standard, and
the property is read-only. Therefore, it is always the same regardless of
the culture used, or the format provider supplied.
RFC1123
R or r
pattern The custom format string is "DDD, dd MMM yyyy HH':' mm': 'ss 'GMT'".

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.

Sortable Represents a custom DateTime format string defined by the


date/time current SortableDateTimePattern property. This pattern is a defined
s pattern; standard, and the property is read-only. Therefore, it is always the same
conforms to regardless of the culture used, or the format provider supplied.
ISO 8601 The custom format string is "yyyy'-'MM'-'dd'T'HH':'mm': 'ss."

Represents a custom DateTime format string defined by the


Short time current ShortTimePattern property.
t
pattern For example, the custom format string for the invariant culture is
"HH:mm."

Represents a custom DateTime format string defined by the


Long time current LongTimePattern property.
T
pattern For example, the custom format string for the invariant culture is
"HH:mm: ss".

Represents a custom DateTime format string defined by the


current UniversalSortableDateTimePattern property. This pattern is a
defined standard and the property is read-only. Therefore, it is always
Universal
the same regardless of the culture used or the format provider supplied.
sortable
u
date/time The custom format string is "yyyy'-'MM'-'dd HH':'mm':'ss'Z'".
pattern
No time zone conversion is done when the date and time is formatted.
Therefore, the application must convert a local date and time to
Coordinated Universal Time (UTC) before using this format specifier.

https://hackr.io/blog/c-sharp-cheat-sheet 10/24
8/24/22, 12:13 PM Download C# Cheat Sheet PDF for Your Quick Reference

Represents a custom DateTime format string defined by the


Universal current FullDateTimePattern property.
sortable
U This pattern is the same as the full date/long time (F) pattern. However,
date/time
pattern formatting operates on the Coordinated Universal Time (UTC) that is
equivalent to the DateTime object being formatted.

Represents a custom DateTime format string defined by the


Year month current YearMonthPattern property.
Y or y
pattern For example, the custom format string for the invariant culture is "yyyy
MMMM".

Custom
patterns –

"MM'/'dd
yyyy" 03/17 2019
"dd.MM.yyyy" 17.03.2019
Custom
format "MM.dd.yyyy 03.17.2019 06:23
HH:mm"
Tuesday, march (2019) : 06:23:00
"dddd,
MMMM
(yyyy):
HH:mm:ss"

Any
other (Unknown
An unknown specifier throws a runtime format exception.
single specifier)
character

Arrays
For creating, modifying, sorting and searching arrays.

PROPERTY DESCRIPTION EXAMPLE

https://hackr.io/blog/c-sharp-cheat-sheet 11/24
8/24/22, 12:13 PM Download C# Cheat Sheet PDF for Your Quick Reference

string[] arrVal = new string[]


{“stud1”, “stud2”, “stud3”};
IsFixedSize checks whether the Array has a fixed size.

arrVal.IsFixedSize;

IsReadOnly Checks whether the Array is read-only. arrVal.IsReadOnly;

Checks whether access to the Array is


IsSynchronized arrVal.IsSynchronized;
synchronized (thread safe).

Gets the total number of elements in all


Length arrVal.Length;
the dimensions of the Array.

LongLength Length in 64-bit integer arrVal.LongLength;

Gets the rank (number of dimensions) of


the Array. For example, a one-dimensional
Rank arrVal.Rank;
array returns 1, a two-dimensional array
returns 2, and so on.

Gets an object used to synchronize Array


SyncRoot arrVal.SyncRoot;
access

Returns a read-only wrapper for the


AsReadOnly() Array.AsReadOnly(arrVal);
specified array.

Searches a value in a one-dimensional Array.BinarySearch(arrVal, obj);


BinarySearch() sorted array using a binary where obj is the object to be
search algorithm. searched.

Array.Clear(arrVal, 0, 2);
Sets a range of elements in an array to If arrVal is an array of integers, the
Clear()
the default value of each element type. elements at position 0 to 2 will be
set to zero after doing Clear().

Clone() Create a shallow copy of the Array. Array.Clone(arrVal);

https://hackr.io/blog/c-sharp-cheat-sheet 12/24
8/24/22, 12:13 PM Download C# Cheat Sheet PDF for Your Quick Reference

Array.ConstrainedCopy(srcArr, 0,
destArr, 3, 5);

Copies a range of elements from an Array where srcArr is the source array,
starting at the specified source index and 0 is the start index from where copy
pastes them to another Array starting at should begin,
ConstrainedCopy()
the specified destination index.
Guarantees that all changes are undone if destArr is the destination array,
the copy does not succeed completely. 3 is the place where copy should
start in the destination array,

5 is the number of elements to copy

conArr = Array.ConvertAll(arrVal,
Converts an array of one data type to an
ConvertAll() new Converter<dtype1, dtype2>
array of another data type.
(method));

Copies a range of elements in one Array Array.Copy(srcArr, destArr, 2);


Copy() to another Array and performs type copies first two elements from
casting and boxing as required. srcArr to destArr

Copies all the elements of the current one- Array.CopyTo(destArr, 4);


CopyTo() dimensional array to the specified one-
dimensional array. copy starts from index 4

Initializes a new instance of the Array Array.CreateInstance(typeof(String),


CreateInstance()
class. length);

Empty() Returns an empty array. arrVal.Empty()

Determines whether the specified object is


Equals() arrVal.Equals(arrVal2);
equal to the current object.

Determines whether the specified array


contains elements that match the Array.Exists(srcArr,
Exists()
conditions defined by the specified “<elementname>”);
predicate.

https://hackr.io/blog/c-sharp-cheat-sheet 13/24
8/24/22, 12:13 PM Download C# Cheat Sheet PDF for Your Quick Reference

Searches for an element that matches the


conditions defined by the specified Array.Find(arrVal, <matching
Find()
predicate, and returns the first occurrence pattern>);
within the entire Array.

Retrieves all the elements that match the


Array.FindAll(arrVal, <matching
FindAll() conditions defined by the specified
pattern>);
predicate.

Searches for an element that matches the


conditions defined by a specified
Array.FindIndex(arrVal, <matching
FindIndex() predicate, and returns the zero-based
pattern>);
index of the first occurrence within an
Array or a portion of it.

Searches for an element that matches the


conditions defined by the specified Array.FindLast(arrVal, <matching
FindLast()
predicate, and returns the last occurrence pattern>);
within the entire Array.

Searches for an element that matches the


conditions defined by a specified
Array.FindLastIndex(arrVal,
FindLastIndex() predicate, and returns the zero-based
<matching pattern>);
index of the last occurrence within an
Array or a portion of it.

Loops through each element of the array


ForEach() Array.ForEach(arrVal, Action)
and performs the specified action

GetEnumerator() Returns an IEnumerator for the Array. arrVal.GetEnumerator()

GetHashCode() default hash function. arrVal.GetHashCode()

Gets a 32-bit integer that represents the


arrVal.GetLength(i) where i is an
GetLength() number of elements in the specified
integer
dimension of the Array.

https://hackr.io/blog/c-sharp-cheat-sheet 14/24
8/24/22, 12:13 PM Download C# Cheat Sheet PDF for Your Quick Reference

Gets a 64-bit integer that represents the


arrVal.GetLongLength(i) where i is
GetLongLength() number of elements in the specified
an integer
dimension of the Array.

Gets the index of the first element of the arrVal.GetLowerBound(i) where i is


GetLowerBound()
specified dimension in the array. an integer

GetType() Gets the Type of the current instance. arrVal.GetType()

Gets the index of the last element of the arrVal.GetUpperBound(i) where i is


GetUpperBound()
specified dimension in the array. an integer

Gets the value of the specified element in


GetValue()
the current Array.

Searches for the specified object and


returns the index of its first occurrence in a
IndexOf() arrVal.IndexOf(object)
one-dimensional array or in a range of
elements in the array.

Initializes every element of the value-type


Initialize() Array by calling the default constructor of
the value type.

Returns the index of the last occurrence of


LastIndexOf() a value in a one-dimensional Array or in a arrVal.LastIndexOf(i)
portion of the Array.

Creates a shallow copy of the current


MemberwiseClone()
Object.

Changes the number of elements of a Array.Resize(ref arrVal, len-2);


Resize() one-dimensional array to the specified where len is the original length of
new size. the array

Reverses the order of the elements in a


Reverse() one-dimensional Array or in a portion of arrVal.Reverse()
the Array.

https://hackr.io/blog/c-sharp-cheat-sheet 15/24
8/24/22, 12:13 PM Download C# Cheat Sheet PDF for Your Quick Reference

Sets the specified element in the current


SetValue() Array.SetValue(arrVal[i])
Array to the specified value.

Sorts the elements in a one-dimensional


Sort() Array.Sort(arrVal)
array.

Returns a string that represents the


ToString() current object. arrVal.ToString()
(Inherited from Object)

Determines whether every element in the


Array.TrueForAll(arrVal, <matching
TrueForAll() array matches the conditions defined by
pattern>)
the specified predicate.

Control Statements
if (true) {...}
if-else else if (true) {...}
else {...}

switch (var)

{
case 1: break;
switch
case 2: break;
default: break;

for for (int i =0; i <=len; i++) {...}

foreach-in foreach (int item in array) {...}

while while (true) {...}

do {...}
do... while
while (true);

https://hackr.io/blog/c-sharp-cheat-sheet 16/24
8/24/22, 12:13 PM Download C# Cheat Sheet PDF for Your Quick Reference

try {...}
catch (Exception e) {...}
try-catch-finally
catch {...}
finally {...}

Regular Expressions
+ match one or more occurrence

* match any occurrence (zero or more)

? match 0 or 1 occurrence

\d \D match decimal digit or non-character

\w \W match any word character

\s \S match white space or no white space

[] match any character inside the square brackets

[^] match any character not present in the square brackets

a|b either a or b

\n new line

\r carriage return

\t tab

Collections
Arraylist

Capacity Gets or sets the number of elements that the ArrayList can contain.

Count Gets the number of elements actually contained in the ArrayList.

https://hackr.io/blog/c-sharp-cheat-sheet 17/24
8/24/22, 12:13 PM Download C# Cheat Sheet PDF for Your Quick Reference

IsFixedSize Gets a value indicating whether the ArrayList has a fixed size.

IsReadOnly Returns whether the ArrayList is read-only

Item Gets or sets the element at the specified index.

Add(object value) Adds an object to the end of the ArrayList

AddRange(ICollection c); Adds the elements of an ICollection to the end of the ArrayList.

Clear(); Removes all elements of an ArrayList.

Contains(object item); Checks whether an element is in the ArrayList.

GetRange(int index, int Returns an ArrayList which represents a subset of the elements in the
count); source ArrayList.

Returns the zero-based index of the first occurrence of a value in the


IndexOf(object);
ArrayList or in a portion of it.

Insert(int index, object


Inserts an element into the ArrayList at the specified index.
value);

InsertRange(int index, Inserts the elements of a collection into the ArrayList at the specified
ICollection c); 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,
Removes a range of elements from the ArrayList
int count);

Reverse(); Reverses the order of the elements in the ArrayList.

SetRange(int index, Copies the elements of a collection over a range of elements in the
ICollection c); ArrayList.

https://hackr.io/blog/c-sharp-cheat-sheet 18/24
8/24/22, 12:13 PM Download C# Cheat Sheet PDF for Your Quick Reference

Sort(); Sorts the elements in the ArrayList.

TrimToSize(); Sets the capacity to the actual number of elements in the ArrayList.

Hashtable

Count Gets the number of key-and-value pairs contained in the Hashtable.

IsFixedSize Gets a value indicating whether the Hashtable has a fixed size

IsReadOnly Gets a value indicating whether the Hashtable is read-only.

Item Gets or sets the value associated with the specified key.

Keys Gets an ICollection containing the keys in the Hashtable.

Values Gets an ICollection containing the values in the Hashtable

Add(object key, object value); Adds an element with the specified key and value into the Hashtable

Clear(); Removes all elements from the Hashtable.

ContainsKey(object key); Determines whether the Hashtable contains a specific key.

ContainsValue(object value); Determines whether the Hashtable contains a specific value.

Remove(object key); Removes the element with the specified key from the Hashtable.

SortedList

Capacity Gets or sets the capacity of the SortedList.

Count Gets the number of elements in the SortedList.

IsFixedSize Checks if the SortedList is of fixed size.

IsReadOnly Checks if the SortedList is read-only.

Item Gets and sets the value associated with a specific key in the SortedList.

https://hackr.io/blog/c-sharp-cheat-sheet 19/24
8/24/22, 12:13 PM Download C# Cheat Sheet PDF for Your Quick Reference

Keys Gets the keys in the SortedList.

Values Gets the values in the SortedList.

Add(object key, object


Adds an element with the specified key and value into the SortedList.
value)

Clear() Removes all elements from the SortedList.

ContainsKey(object
Checks if the SortedList contains a specific key.
key);

ContainsValue(object
Checks if the SortedList contains a specific value.
value);

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.

GetKeyList(); Returns list of keys in the SortedList

GetValueList(); Returns list of values in the SortedList

IndexOfKey(object
Returns the zero-based index of the specified key in the SortedList.
key);

IndexOfValue(object Returns the zero-based index of the first occurrence of the specified value
value); in the SortedList.

Remove(object key); Removes the element with the specified key from the SortedList.

RemoveAt(int index); Removes the element at the specified index of SortedList.

TrimToSize(); Sets the capacity to the actual number of elements in the SortedList.

Stack

Count Number of elements in the Stack.

https://hackr.io/blog/c-sharp-cheat-sheet 20/24
8/24/22, 12:13 PM Download C# Cheat Sheet PDF for Your Quick Reference

Clear(); Removes all elements from the Stack.

Contains(object obj); Checks if an element is in the Stack.

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.

Push(object obj); Inserts an object at the top of the Stack.

ToArray(); Copies the Stack to a new array.

Queue

Count number of elements in the Queue.

Clear(); Removes all elements from the Queue.

Contains(object obj); Checks if the specified object is present in the Queue.

Dequeue(); Removes and returns the object at the beginning of the Queue.

Enqueue(object obj); Adds an object to the end of the Queue.

ToArray(); Copies the Queue to a new array.

TrimToSize(); Sets the capacity to the actual number of elements in the Queue.

Dictionary

Count Gets the total number of elements exists in the Dictionary<TKey,TValue>.

IsReadOnly Returns a boolean after checking if the Dictionary<TKey,TValue> is read-only.

Item Gets or sets the element with the specified key in the Dictionary<TKey,TValue>.

Keys Returns collection of keys of Dictionary<TKey,TValue>.

Values Returns collection of values in Dictionary<TKey,TValue>.

https://hackr.io/blog/c-sharp-cheat-sheet 21/24
8/24/22, 12:13 PM Download C# Cheat Sheet PDF for Your Quick Reference

Add Add key-value pairs in Dictionary<TKey, TValue> collection.

Remove Removes the first occurrence of specified item from the Dictionary<TKey, TValue>.

ContainsKey Checks if the specified key exists in Dictionary<TKey, TValue>.

ContainsValue Checks if the specified value exists in Dictionary<TKey, TValue>.

Clear Removes all the elements from Dictionary<TKey, TValue>.

Returns true and assigns the value with specified key, if key does not exists then
TryGetValue
return false.

Exception Handling

try{
} catch (Exception e){
throw;
}

Methods

No return type public void MyMethod(){}

static method, no object needed to call method public static void MyMethod(){}

public returnType MyMethod(){

with return type return val;

public void MyMethod(String s, int i) {


passing parameters
}

Classes

https://hackr.io/blog/c-sharp-cheat-sheet 22/24
8/24/22, 12:13 PM Download C# Cheat Sheet PDF for Your Quick Reference

Class MyClass
{
/*Class definition*/
}
Object creation –
MyClass ClassObj = new MyClass();

Partial Class
Classes within the same namespace can be split into smaller classes with same name.

// PartialClass1.cs // PartialClass2.cs
using System; using System;
namespace PartialClasses namespace PartialClasses
{ {
public partial class PartialClass public partial class PartialClass
{ {
public void HelloWorld() public void HelloUser()
{ {
Console.WriteLine("Hello, world!"); Console.WriteLine("Hello, user!");
} }
} }
} }

A single instance is enough to call the methods of these partial classes.

PartialClass pc = new PartialClass();


pc.HelloWorld();
pc.HelloUser();

File Handling
Check the existence of the file in
File.Exists File.Exists(path)
the specified path

File.ReadAllLines(path)
Read all the lines from the file
File.ReadAllLines Console.WriteLines(File.ReadAllLines(path)
specified by the path
// Write to console

https://hackr.io/blog/c-sharp-cheat-sheet 23/24
8/24/22, 12:13 PM Download C# Cheat Sheet PDF for Your Quick Reference

Read all the text from the file and


File.ReadAllText File.ReadAllText(path)
store it as a single string

Copy content from one file to


File.Copy File.Copy(srcfilepath, destfilepath);
another

Delete an existing file from the


File.Delete File.Delete(path)
specified path

https://hackr.io/blog/c-sharp-cheat-sheet 24/24

You might also like