Professional Documents
Culture Documents
View offers
Home / Articles / C# / Download C# Cheat Sheet PDF for Your Quick Reference Disclosure: Hackr.io is supported by its
audience. When you purchase through
Ramya Shankar | 12 Dec, 2022 links on our site, we may earn an
affiliate commission.
C# Introduction
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>;
Naming Conventions
Class StudentClass
Method GetMarks
Local variable firstName
Constant Percentile
Data types
Initialisation of variables
int i = 7;
byte b = 255;
String s = “hackr.io”;
char c = ‘h’;
Constant values
Operators
Operator Description
String concatenation
+ (“Welcome to ” +
websiteName)
arrVal.ToString()
Calculations, passing
() parameters etc…
(i+10)*(i-10); multiply(i, j)
Logical AND
&&
if (isSingle && isMatching)
Suggested Course
String Operations
Make clone of
Clone() str2 = str1.Clone()
string.
Compare
Programming two
Data Science DevOps Design Login
strings and returns
integer value as
CompareTo() str2.CompareTo(str1) In this article
output. It returns 0
for true and 1 for C# Introduction
false.
checks whether
specified character
Contains() or string is exists or str2.Contains(“hack”)
not in the string
value.
checks whether
specified character
EndsWith() str2.EndsWith(“io”);
is the last character
of string or not.
compares two
string and returns
Equals() Boolean value true str2.Equals(str1)
as output if they are
equal, false if not
returns HashValue
GetHashCode() str1.GetHashCode()
of specified string.
returns the
GetType() System.Type of str1.GetType()
current instance.
returns the
Stystem.TypeCode
GetTypeCode() str1.GetTypeCode()
for class
System.String.
returns length of
Length str1.Length;
string.
deletes all the
characters from
Remove() beginning to str1.Remove(i);
specified index
position.
replaces the
Replace() specified character str1.Replace(‘a’, ‘e’);
with another
str1 = “Good
morning and
Welcome”;
This method splits
String sep =
Split() the string based on
{“and”};
specified value.
strArray =
str1.Split(sep,
StringSplitOptions.No
Checks whether
the first character
StartsWith() str1.StartsWith(“H”)
of string is same as
specified character.
This method
Substring() str1.Substring(1, 7);
returns substring.
It removes extra
whitespaces from
Trim() str1.Trim();
beginning and
ending of string.
Modifiers
Provides a new
implementation of a virtual
override
member inherited from a base
class
Declares a method or an
accessor whose
virtual implementation can be
changed by an overriding
member in a derived class
Date/Time formatting
DateTime dt = new
gives output as –
DateTime();
01-01-0001 00:00:00
dt.ToString();
Represents a
custom DateTime
format string
defined by the
current
ShortDatePattern
d Short date pattern property.
Represents a
combination of the
Full date/time long date (D) and
f
pattern (short time) short time (t)
patterns, separated
by a space.
Represents a
custom DateTime
format string
defined by the
current
FullDateTimePattern
Full date/time property.
F
pattern (long time)
For example, the
custom format
string for the
invariant culture is
"dddd, dd MMMM
yyyy HH:mm: ss."
Represents a
combination of the
General date/time short date (d) and
g
pattern (short time) short time (t)
patterns, separated
by a space.
Represents a
combination of the
General date/time short date (d) and
G
pattern (long time) long time (T)
patterns, separated
by a space.
Represents a
custom DateTime
format string
defined by the
current
MonthDayPattern
M or m Month day pattern property.
For example, the
custom format
string for the
invariant culture is
"MMMM dd."
o Round-trip Represents a
date/time pattern 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 string
can be parsed back
using Parse or
ParseExact with the
correct Kind
property value.
The custom format
string is "yyyy'-
'MM'-'dd'T'HH':'
mm': 'ss.fffffffK."
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.
The custom format
R or r RFC1123 pattern
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.
Represents a
custom DateTime
format string
defined by the
current
ShortTimePattern
t Short time pattern property.
Represents a
custom DateTime
format string
defined by the
current
LongTimePattern
T Long time pattern property.
Represents a
custom DateTime
format string
defined by the
current
FullDateTimePattern
property.
Represents a
custom DateTime
format string
defined by the
current
YearMonthPattern
Y or y Year month pattern property.
Custom patterns –
"MM'/'dd yyyy" 03/17 2019
"dd.MM.yyyy" 17.03.2019
Custom format 03.17.2019 06:23
"MM.dd.yyyy
HH:mm" Tuesday, march
"dddd, MMMM (2019) : 06:23:00
(yyyy): HH:mm:ss"
An unknown
Any other single specifier throws a
(Unknown specifier)
character runtime format
exception.
Arrays
For creating, modifying, sorting and searching arrays.
string[] arrVal =
new string[]
checks whether the {“stud1”, “stud2”,
IsFixedSize Array has a fixed “stud3”};
size.
arrVal.IsFixedSize;
Checks whether
IsReadOnly the Array is read- arrVal.IsReadOnly;
only.
Checks whether
access to the Array
IsSynchronized arrVal.IsSynchronized
is synchronized
(thread safe).
Length in 64-bit
LongLength arrVal.LongLength;
integer
Returns a read-only
AsReadOnly() wrapper for the Array.AsReadOnly(arr
specified array.
Searches a value in
Array.BinarySearch(a
a one-dimensional
obj); where obj is
BinarySearch() sorted array using a
the object to be
binary search
searched.
algorithm.
Array.Clear(arrVal,
0, 2);
Sets a range of
elements in an If arrVal is an array
Clear() array to the default of integers, the
value of each elements at
element type. position 0 to 2 will
be set to zero after
doing Clear().
Create a shallow
Clone() Array.Clone(arrVal);
copy of the Array.
Array.ConstrainedCop
0, destArr, 3, 5);
Copies a range of
where srcArr is the
elements from an
source array,
Array starting at the
specified source 0 is the start index
index and pastes from where copy
them to another should begin,
Array starting at the
ConstrainedCopy() destArr is the
specified
destination index. destination array,
Guarantees that all
3 is the place
changes are
where copy should
undone if the copy
start in the
does not succeed
destination array,
completely.
5 is the number of
elements to copy
conArr =
Converts an array
Array.ConvertAll(arrV
of one data type to
ConvertAll() new
an array of another
Converter<dtype1,
data type.
dtype2> (method));
Initializes a new
Array.CreateInstance
CreateInstance() instance of the
length);
Array class.
Returns an empty
Empty() arrVal.Empty()
array.
Determines
whether the
Equals() specified object is arrVal.Equals(arrVal2)
equal to the current
object.
Determines
whether the
specified array
contains elements Array.Exists(srcArr,
Exists()
that match the “<elementname>”);
conditions defined
by the specified
predicate.
Searches for an
element that
matches the
conditions defined Array.Find(arrVal,
Find() by the specified <matching
predicate, and pattern>);
returns the first
occurrence within
the entire Array.
Searches for an
element that
matches the
conditions defined
by a specified Array.FindIndex(arrVa
FindIndex() predicate, and <matching
returns the zero- pattern>);
based index of the
first occurrence
within an Array or a
portion of it.
Searches for an
element that
matches the
conditions defined Array.FindLast(arrVal,
FindLast() by the specified <matching
predicate, and pattern>);
returns the last
occurrence within
the entire Array.
Returns an
GetEnumerator() IEnumerator for the arrVal.GetEnumerator
Array.
default hash
GetHashCode() arrVal.GetHashCode(
function.
Gets a 32-bit
integer that
represents the
arrVal.GetLength(i)
GetLength() number of elements
where i is an integer
in the specified
dimension of the
Array.
Gets a 64-bit
integer that
represents the
arrVal.GetLongLength
GetLongLength() number of elements
where i is an integer
in the specified
dimension of the
Array.
Initializes every
element of the
value-type Array by
Initialize()
calling the default
constructor of the
value type.
Creates a shallow
MemberwiseClone() copy of the current
Object.
Returns a string
that represents the
ToString() current object. arrVal.ToString()
(Inherited from
Object)
Determines
whether every
element in the array Array.TrueForAll(arrVa
TrueForAll() matches the <matching
conditions defined pattern>)
by the specified
predicate.
Control Statements
if (true) {...}
if-else else if (true) {...}
else {...}
switch (var)
{
case 1: break;
switch
case 2: break;
default: break;
do {...}
do... while
while (true);
try {...}
catch (Exception e) {...}
try-catch-finally
catch {...}
finally {...}
Regular Expressions
? match 0 or 1 occurrence
a|b either a or b
\n new line
\r carriage return
\t tab
Collections
Arraylist
Hashtable
SortedList
Stack
Queue
Dictionary
Exception Handling
try{
} catch (Exception e){
throw;
}
Methods
No return type public void MyMethod(){}
Classes
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 PartialCl public partial class PartialCl
{ {
public void HelloWorld() public void HelloUser()
{ {
Console.WriteLine("Hello, worl Console.WriteLine("Hello, user
} }
} }
} }
File Handling
Check the
existence of the file
File.Exists File.Exists(path)
in the specified
path
Read all the lines File.ReadAllLines(path
from the file
File.ReadAllLines Console.WriteLines(F
specified by the
path // Write to console
Delete an existing
File.Delete file from the File.Delete(path)
specified path
Explore More
search... SHOW ALL
Subscribe to
our newsletter
Enter email here
Subscribe Now