Show Menu
Cheatography

C# for Potatoes Cheat Sheet by

c# syntax with examples

String Manipu­lation

ToLower
Converts all characters to lowercase.
str.To­Lower()   "­HEL­LO".T­oL­ower()   // "­hel­lo"
ToUpper
Converts all characters to uppercase.
str.To­Upper()   "­hel­lo".T­oU­pper()   // "­HEL­LO"
Trim
Removes leading and trailing white-­space charac­ters.
str.Trim()   " hello ".Trim()   // "­hel­lo"
TrimStart
Removes leading white-­space charac­ters.
str.Tr­imS­tart()   " hello ".Tr­imS­tart()   // "­hello "
TrimEnd
Removes trailing white-­space charac­ters.
str.Tr­imEnd()   " hello ".Tr­imEnd()   // " hello"
Substring
Retrieves a substring starting at a specified position.
str.Su­bst­ring(0, 5)   "­hello world".S­ub­str­ing(0, 5)   // "­hel­lo"
Replace
Replaces all occurr­ences of a specified string with another
str.Re­pla­ce(­"­wor­ld", "­C#")   "­hello world".R­ep­lac­e("w­orl­d", "­C#") // "­hello C#"
Split
Splits a string into an array based on a delimiter.
str.Sp­lit(' ')   "­hello world".S­plit(' ')   // ["he­llo­", "­wor­ld"]
Join
Concat­enates an array into a single string with a delimiter
string.Jo­in(­" ", words)   string.Jo­in(­" ", new[] { "­hel­lo", "­wor­ld" })   // "­hello world"
Contains
Checks if a string contains a specified substring.
str.Co­nta­ins­("wo­rld­")   "­hello world".C­on­tai­ns(­"­wor­ld")   // true
IndexOf
Finds the first occurrence of a substring.
str.In­dex­Of(­"­wor­ld")   "­hello world".I­nd­exO­f("w­orl­d")   // 6
LastIn­dexOf
Finds the last occurrence of a substring.
str.La­stI­nde­xOf­("wo­rld­")   "­hello world world".L­as­tIn­dex­Of(­"­wor­ld")   // 12
StartsWith
Checks if a string starts with a specified substring.
str.St­art­sWi­th(­"­hel­lo")   "­hello world".S­ta­rts­Wit­h("h­ell­o")   // true
EndsWith
Checks if a string ends with a specified substring.
str.En­dsW­ith­("wo­rld­")   "­hello world".E­nd­sWi­th(­"­wor­ld")   // true
IsNull­OrEmpty
Checks if a string is null or empty.
string.Is­Nul­lOr­Emp­ty(str)   string.Is­Nul­lOr­Emp­ty(­"­")   // true
IsNull­OrW­hit­eSpace
Checks if a string is null, empty, or whites­pace.
string.Is­Nul­lOr­Whi­teS­pac­e(str)   string.Is­Nul­lOr­Whi­teS­pac­e(" ")   // true
Format
Replaces format items in a string with the string repres­ent­ation of corres­ponding objects.
string.Fo­rma­t("H­ello, {0}!", "­wor­ld")   // "­Hello, world!­"
PadLeft
Pads a string on the left with a specified character.
str.Pa­dLe­ft(10)   "­hel­lo".P­ad­Lef­t(10)   // " hello"
PadRight
Pads a string on the right with a specified character.
str.Pa­dRi­ght(10)   "­hel­lo".P­ad­Rig­ht(10)   // "­hello "
ToChar­Array
Converts the string to a character array.
str.To­Cha­rAr­ray()   "­hel­lo".T­oC­har­Array()   // ['h', 'e', 'l', 'l', 'o']
Compare
Compares two strings and returns an integer indicating their relative position in the sort order.
string.Co­mpa­re(­"­app­le", "­ban­ana­")   // -1
Equals
Checks if two strings are equal.
"­hel­lo".E­qu­als­("he­llo­")   // true

Errors

System­Exc­eption
Base class for all system­-de­fined except­ions.
catch (Syste­mEx­ception ex)
Argume­ntE­xce­ption
Thrown when one of the arguments provided to a method is not valid.
throw new Argume­ntE­xce­pti­on(­"­mes­sag­e", "­par­amN­ame­");
Argume­ntN­ull­Exc­eption
Thrown when a null argument is passed to a method that does not accept it.
throw new Argume­ntN­ull­Exc­ept­ion­("pa­ram­Nam­e");
Argume­ntO­utO­fRa­nge­Exc­eption
Thrown when an argument is outside the range of valid values.
throw new Argume­ntO­utO­fRa­nge­Exc­ept­ion­("pa­ram­Nam­e");
Invali­dOp­era­tio­nEx­ception
Thrown when a method call is invalid for the object's current state.
throw new Invali­dOp­era­tio­nEx­cep­tio­n("m­ess­age­");
IndexO­utO­fRa­nge­Exc­eption
Thrown when an index is outside the bounds of an array or collec­tion.
throw new IndexO­utO­fRa­nge­Exc­ept­ion­("me­ssa­ge");
FileNo­tFo­und­Exc­eption
Thrown when an attempt to access a file that does not exist on disk is made.
throw new FileNo­tFo­und­Exc­ept­ion­("me­ssa­ge", innerE­xce­ption);
IOExce­ption
Base class for exceptions that occur during I/O operat­ions.
catch (IOExc­eption ex)
NullRe­fer­enc­eEx­ception
Thrown when there is an attempt to derefe­rence a null object reference.
throw new NullRe­fer­enc­eEx­cep­tio­n("m­ess­age­");
Overfl­owE­xce­ption
Thrown when an arithm­etic, casting, or conversion operation in a checked context overflows.
throw new Overfl­owE­xce­pti­on(­"­mes­sag­e");
Format­Exc­eption
Thrown when the format of an argument is invalid, e.g., parsing numbers.
throw new Format­Exc­ept­ion­("me­ssa­ge");
Unauth­ori­zed­Acc­ess­Exc­eption
Thrown when the operating system denies access to a file or directory.
throw new Unauth­ori­zed­Acc­ess­Exc­ept­ion­("me­ssa­ge");
NotSup­por­ted­Exc­eption
Thrown when a method or operation is not supported.
throw new NotSup­por­ted­Exc­ept­ion­("me­ssa­ge");
Divide­ByZ­ero­Exc­eption
Thrown when there is an attempt to divide an integer by zero.
throw new Divide­ByZ­ero­Exc­ept­ion­("me­ssa­ge");
Timeou­tEx­ception
Thrown when an operation exceeds the allotted time.
throw new Timeou­tEx­cep­tio­n("m­ess­age­");

List

List<T­Â­yp­e> listName = new List<T­Â­>();
Declares a new list.
listNa­Â­me.C­ount
Gets the number of elements contained in the List<T­Â­>.
listNa­Â­me.A­­dd(T);
Adds an object to the end of the List<T­Â­>.
listNa­Â­me.C­­le­­ar();
Removes all elements from the List<T­Â­>.
listNa­Â­me.C­­on­­tai­Â­ns(T);
Determines whether an element is in the List<T­Â­>.
listNa­Â­me.E­­qu­­als­Â­(O­b­j­ect);
Determines whether the specified object is equal to the current object.
listNa­Â­me.I­­nd­­exO­Â­f(T);
Searches for the specified object and returns the zero-based index of the first occurrence within the entire List<T­Â­>.
listNa­Â­me.R­­em­­ove(T);
Removes the first occurrence of a specific object from the List<T­Â­>.
listNa­Â­me.R­­em­­ove­Â­At­(­I­nt32);
Removes the element at the specified index of the List<T­Â­>.

Arrays

Initia­lizing array
int[] numbers = { 1, 2, 3, 4, 5 };
Accessing element
int firstN­umber = number­s[0]; // 1
Modifying element
numbers[0] = 10; // { 10, 2, 3, 4, 5 }
For Loop
for (int i = 0; i < number­s.L­ength; i++) {
 ­ ­Con­sol­e.W­rit­eLi­ne(­num­ber­s[i]);
}
Foreach Loop
foreach (int number in numbers) {
 ­ ­Con­sol­e.W­rit­eLi­ne(­num­ber);
}
Index of Element
int index = Array.I­nd­exO­f(n­umbers, 3); // 2
Element based on condition
int foundN­umber = Array.F­in­d(n­umbers, n => n > 2); // 10
Sorting
Array.S­or­t(n­umb­ers); // { 2, 3, 4, 10, 50 }
Reverse
Array.R­ev­ers­e(n­umb­ers); // { 50, 10, 4, 3, 2 }
Copy
Array.C­op­y(n­umbers, copy, number­s.L­ength); // copy = { 50, 10, 4, 3, 2 }
Clear
Array.C­le­ar(­num­bers, 0, number­s.L­ength); // { 0, 0, 0, 0, 0 }
Resize
Array.R­es­ize(ref numbers, 7); // { 0, 0, 0, 0, 0, 0, 0 }
ToList
List<i­nt> number­sList = number­s.T­oLi­st();

LINQ

Where
var evenNu­mbers = number­s.W­here(n => n % 2 == 0);
Select
var squares = number­s.S­elect(n => n * n);
OrderBy
var sorted­Numbers = number­s.O­rde­rBy(n => n);
OrderB­yDe­sce­nding
var sorted­Num­ber­sDesc = number­s.O­rde­rBy­Des­cen­ding(n => n);
ThenBy
var sorted­People = people.Or­derBy(p => p.Last­Nam­e).T­he­nBy(p => p.Firs­tName);
ThenBy­Des­cending
var sorted­Peo­pleDesc = people.Or­derBy(p => p.Last­Nam­e).T­he­nBy­Des­cen­ding(p => p.Firs­tName);
GroupBy
var groupe­dByAge = people.Gr­oupBy(p => p.Age);
Join
var joinQuery = custom­ers.Jo­in(­orders, customer => custom­er.Id, order => order.C­us­tom­erId, (customer, order) => new { custom­er.N­ame, order.O­rderId });
GroupJoin
var groupJ­oin­Query = custom­ers.Gr­oup­Joi­n(o­rders, customer => custom­er.Id, order => order.C­us­tom­erId, (customer, orders) => new { custom­er.N­ame, Orders = orders });
SelectMany
var allOrders = custom­ers.Se­lec­tMany(c => c.Orders);
Take
var firstT­hre­eNu­mbers = number­s.T­ake(3);
Skip
var allBut­Fir­stT­hre­eNu­mbers = number­s.S­kip(3);
TakeWhile
var takeWh­ile­Query = number­s.T­ake­While(n => n < 5);
SkipWhile
var skipWh­ile­Query = number­s.S­kip­While(n => n < 5);
Distinct
var distin­ctN­umbers = number­s.D­ist­inct();
Union
var unionQuery = number­s1.U­ni­on(­num­bers2);
Intersect
var inters­ect­Query = number­s1.I­nt­ers­ect­(nu­mbe­rs2);
Except
var except­Query = number­s1.E­xc­ept­(nu­mbe­rs2);
Concat
var concat­Query = number­s1.C­on­cat­(nu­mbe­rs2);
Any
bool hasEve­nNu­mbers = number­s.Any(n => n % 2 == 0);
All
bool allPos­itive = number­s.All(n => n > 0);
Contains
bool contai­nsN­umber = number­s.C­ont­ain­s(5);
First
int firstN­umber = number­s.F­irst();
FirstO­rDe­fault
int firstO­rDe­fau­ltN­umber = number­s.F­irs­tOr­Def­ault();
Last
int lastNumber = number­s.L­ast();
LastOr­Default
int lastOr­Def­aul­tNumber = number­s.L­ast­OrD­efa­ult();
Single
int single­Number = number­s.S­ingle(n => n == 5);
Single­OrD­efault
int single­OrD­efa­ult­Number = number­s.S­ing­leO­rDe­fault(n => n == 5);
Count
int count = number­s.C­ount();
Sum
int sum = number­s.S­um();
Average
double average = number­s.A­ver­age();
Min
int min = number­s.M­in();
Max
int max = number­s.M­ax();

DateTime

Now
Gets the current date and time.
DateTime now = DateTi­me.Now;    // e.g., "­202­4-07-28 14:35:­00"
UtcNow
Gets the current date and time in Coordi­nated Universal Time (UTC).
DateTime utcNow = DateTi­me.U­tcNow;    // e.g., "­202­4-07-28 18:35:­00"
Today
Gets the current date with the time component set to 00:00:00.
DateTime today = DateTi­me.T­oday;    // e.g., "­202­4-07-28 00:00:­00"
Date
Gets the date component of the DateTime instance.
DateTime date = now.Date;    // e.g., "­202­4-07-28 00:00:­00"
Day
Gets the day of the month repres­ented by the DateTime instance.
int day = now.Day;    // e.g., 28
Month
Gets the month component of the DateTime instance.
int month = now.Month;    // e.g., 7
Year
Gets the year component of the DateTime instance.
int year = now.Year;    // e.g., 2024
Hour
Gets the hour component of the DateTime instance.
int hour = now.Hour;    // e.g., 14
Minute
Gets the minute component of the DateTime instance.
int minute = now.Mi­nute;    // e.g., 35
Second
Gets the second component of the DateTime instance.
int second = now.Se­cond;    // e.g., 0
DayOfWeek
Gets the day of the week repres­ented by the DateTime instance.
DayOfWeek dayOfWeek = now.Da­yOf­Week;    // e.g., DayOfW­eek.Sunday
DayOfYear
Gets the day of the year repres­ented by the DateTime instance.
int dayOfYear = now.Da­yOf­Year;    // e.g., 210
AddDays
Adds the specified number of days to the DateTime instance.
DateTime futureDate = now.Ad­dDa­ys(5);    // e.g., "­202­4-08-02 14:35:­00"
AddMonths
Adds the specified number of months to the DateTime instance.
DateTime futureDate = now.Ad­dMo­nth­s(1);    // e.g., "­202­4-08-28 14:35:­00"
AddYears
Adds the specified number of years to the DateTime instance
DateTime futureDate = now.Ad­dYe­ars(1);    // e.g., "­202­5-07-28 14:35:­00"
AddHours
Adds the specified number of hours to the DateTime instance.
DateTime futureDate = now.Ad­dHo­urs(5);    // e.g., "­202­4-07-28 19:35:­00"
AddMinutes
Adds the specified number of minutes to the DateTime instance.
DateTime futureDate = now.Ad­dMi­nut­es(30);    // e.g., "­202­4-07-28 15:05:­00"
AddSeconds
Adds the specified number of seconds to the DateTime instance.
DateTime futureDate = now.Ad­dSe­con­ds(30);    // e.g., "­202­4-07-28 14:35:­30"
AddMil­lis­econds
Adds the specified number of millis­econds to the DateTime instance.
DateTime futureDate = now.Ad­dMi­lli­sec­ond­s(500);    // e.g., "­202­4-07-28 14:35:­00.5­00­"
AddTicks
Adds the specified number of ticks to the DateTime instance.
DateTime futureDate = now.Ad­dTi­cks­(10­00000);    // e.g., "­202­4-07-28 14:35:­00.0­00­100­0"
Subtract
Subtracts the specified date and time from this instance.
TimeSpan duration = now.Su­btr­act­(pa­stD­ate);    // e.g., "­2.0­0:0­0:0­0" (2 days)
ToString
Converts the value of the DateTime instance to its equivalent string repres­ent­ation.
string str = now.To­Str­ing­("yy­yy-­MM-dd HH:mm:­ss");    // "­202­4-07-28 14:35:­00"
Parse
Converts the string repres­ent­ation of a date and time to its DateTime equiva­lent.
DateTime dt = DateTi­me.P­ar­se(­"­202­4-07-28 14:35:­00");
TryParse
Converts the string repres­ent­ation of a date and time to its DateTime equivalent and returns a value that indicates whether the conversion succeeded.
bool success = DateTi­me.T­ry­Par­se(­"­202­4-07-28 14:35:­00", out DateTime dt);

Variables

int
int myNum = 5;
double
double myDoub­leNum = 5.99D;
char
char myLetter = 'D';
bool
bool myBool = true;
string
string myText = "­Hel­lo";
float
float value = 6.3F;

Naming Conven­tions

Class
MyClass
Method
MyMethod
Local Variable
myLoca­lVa­riable
Private Variable
_myPri­vat­eVa­riable
Constant
MyConstant

Assignemnt

=
Simple assign­Â­ment.
+=
Addition assign­Â­ment.
-=
Subtra­Â­Â­ction assign­Â­ment.
*=
Multip­Â­Â­l­i­c­Â­ation assign­Â­ment.
/=
Division assign­Â­ment.
%=
Remainder assign­Â­ment.
&&
AND assign­Â­ment.
||
OR assign­Â­ment.

Exception Handling

try {
 ­ // code that might throw an exception
}
catch (Exception ex) {
 ­ // handle exception }
finally {
 ­ // cleanup code
}

Conditions

if (condi­tion) {
// if the condition is True
}
else {
// if the condition is False
}
switch­(ex­pre­ssion) {
 ­ case x:
   // code block
    break;
  case y:
   // code block
   break;
  default:
  // code block
   break;
}
while (condi­tion) {
 ­ // code block to be executed
}
foreach (type variab­leName in arrayName) {
 ­ // code block to be executed
}
for (int i = 0; i < 5; i++) {
 ­ ­Con­sol­e.W­rit­eLi­ne(i);
}
do {...} while (true);
 

Commenting

// Single­-Line Comment
/* Multip­le-Line Comment */

Compar­ision

<
<
<=
>=
==
!=

Type Conver­sions

ToBoolean
ToByte
ToChar
ToDateTime
ToDecimal
ToDouble
ToInt64
ToInt32
ToInt16
ToSbyte
ToSingle
ToString
ToType
ToUInt16
ToUInt32

Modifiers

abstract
abstract class Shape { ... }
async
private async void Task() { ... }
const
const int X = 0;
event
public event Sample­Â­Ev­e­n­tH­­andler Sample­Â­Event;
delegate
public delegate void Sample­Â­Ev­e­n­tH­­and­Â­le­r­(­object sender, Sample­Â­Ev­e­n­tArgs e;
new
public Random random = new Random();
override
public override void ToString() { ... }
readonly
private readonly int value = 6;
static
static int = 7;

Other Operators

sizeof()
Returns the size of a data type
typeof()
Returns the type of a class
&
Returns the address of a variable
*
Pointer to a variable
? :
Condit­ional expression
is
Determines whether an object is of a specific type
as
Cast without raising an exception if the cast fails

Inheri­tance

public class Animal {
 ­ ­public virtual void MakeSo­und() {
 ­ ­ ­Con­sol­e.W­rit­eLi­ne(­"Some sound");
   }
}
public class Dog : Animal {
 ­ ­public override void MakeSo­und() {
 ­ ­  Console.WriteLine("Bark");
 ­  }
}

Webstorm

Double Shift
Search Everywhere Quickly find any file, action, class, symbol, tool window, or setting in WebStorm, in your project, and in the current Git reposi­tory.
Ctrl Shift A
Find Action Find a command and execute it, open a tool window, or search for a setting.
Double Ctrl
Run Anything Launch run/debug config­ura­tions, run npm and yarn scripts, and reopen recent projects.
AltEnter
Show Context Actions Quick-­fixes for highli­ghted errors and warnings, intention actions for improving and optimizing your code.
F2 or Shift F2
Navigate between code issues Jump to the next or previous highli­ghted error.
Ctrl E
View recent files Select a recently opened file from the list.
Ctrl W or Ctrl Shift W
Extend or shrink selection Increase or decrease the scope of selection according to specific code constr­ucts.
Ctrl / or Ctrl Shift /
Add/remove line or block comment Comment out a line or block of code.
Alt F7
Find Usages Show all places where a code element is used across your project.
   
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          Numeric Formats Cheat Sheet
          C# CheatSheet Cheat Sheet
          C# Collection Cheat Sheet

          More Cheat Sheets by PotatoCodes

          Slack Keyboard Shortcuts