Cheatsheet for C#*
Steve Mak
Posted on May 13, 2020
Reference
https://en.wikipedia.org/wiki/C_Sharp_syntax#Object_initializers
https://docs.microsoft.com/en-us/dotnet/csharp/
Variables and Types
C# type keyword | .NET type | Example | Default Value |
---|---|---|---|
Primitive Data Types | |||
bool | System.Boolean | bool myBoolean = true; | false |
byte | System.Byte | 0 | |
sbyte | System.SByte | 0 | |
char | System.Char | char myChar = 'a'; | '\0' (U+0000) |
decimal | System.Decimal | 0 | |
double | System.Double | double myDouble = 1.75; | 0 |
float | System.Single | float myFloat = 1f; | 0 |
int | System.Int32 | int a = 123; System.Int32 b = 123; |
0 |
uint | System.UInt32 | 0 | |
long | System.Int64 | 0 | |
ulong | System.UInt64 | 0 | |
short | System.Int16 | 0 | |
ushort | System.UInt16 | 0 | |
Reference Data Types | null | ||
object | System.Object | ||
string | System.String | string myName = "John"; |
Access Modifier
public protected internal private
protected internal
private protected
Modifier
abstract async await const event
extern in new out override
readonly sealed static unsafe virtual
volatile
Statement Keywords
if else switch case
do for foreach in while
break continue default goto return yield
throw try-catch try-finally try-catch-finally
checked unchecked
fixed
lock
Method Parameters
// Parameters declared for a method without in, ref or out, are passed to the called method by value.
// *params* specifies that this parameter may take a variable number of arguments.
public static void UseParams2(params object[] list)
{
...
UseParams2({ 2, 'b', "test", "again" });
// *in* specifies that this parameter is passed by reference but is only read by the called method.
InArgExample(readonlyArgument);
..
void InArgExample(in int number)
{
// Uncomment the following line to see error CS8331
//number = 19;
}
// *ref* specifies that this parameter is passed by reference and may be read or written by the called method.
void Method(ref int refArgument)
{
refArgument = refArgument + 44;
}
int number = 1;
Method(ref number);
Console.WriteLine(number);
// Output: 45
// *out* specifies that this parameter is passed by reference and is written by the called method.
int initializeInMethod;
OutArgExample(out initializeInMethod);
Console.WriteLine(initializeInMethod); // value is now 44
void OutArgExample(out int number)
{
number = 44;
}
Null Conditional Operator (?.)
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(FirstName)));
Enums
public enum CarType
{
Toyota = 1,
Honda = 2,
Ford = 3,
}
CarType myCarType = CarType.Toyota;
Struct
public struct Coords
{
public Coords(double x, double y)
{
X = x;
Y = y;
}
public double X { get; }
public double Y { get; }
public override string ToString() => $"({X}, {Y})";
}
Strings
string myString = "A string.";
String myString = "A string.";
string emptyString = String.Empty;
string anotherEmptyString = "";
string fullName = firstName + " " + lastName;
sentence += "chess.";
string sumCalculation = String.Format("{0} + {1} = {2}", x, y, sum);
// Use string interpolation to concatenate strings.
string str = $"Hello {userName}. Today is {date}."; // Interpolated string
Arrays
/*
* Single Dimensional Arrays
*/
int[] nums = { 1, 2, 3, 4, 5 };
int[] nums = new int[10];
/*
* Multidimensional Arrays
*/
int[,] matrix = new int[2,2];
matrix[0,0] = 1;
matrix[0,1] = 2;
matrix[1,0] = 3;
matrix[1,1] = 4;
int[,] predefinedMatrix = new int[2,2] { { 1, 2 }, { 3, 4 } };
Lists
List<int> numbers = new List<int>();
int[] array = new int[] { 1, 2, 3 };
numbers.AddRange(array);
Dictionaries
Dictionary<string, long> phonebook = new Dictionary<string, long>();
phonebook.Add("Alex", 4154346543);
phonebook["Jessica"] = 4159484588;
Conditionals
/*
* if-else
*/
if (a == b) {
// We already know this part
} else {
// a and b are not equal... :/
}
/*
* for-loops
*/
for(int i = 0; i < 16; i++)
{
if(i == 12)
{
break;
}
}
/*
* while-loops
*/
while(n == 0)
{
Console.WriteLine("N is 0");
n++;
}
Methods
public static int Multiply(int a, int b)
{
return a * b;
}
Interface
interface ISkills
{
void language();
void sport();
}
Class
abstract class Staff:Object, ISkills // inherits a class and implements an interface
{
public enum StaffType { Teacher, Student }; // enum
private StaffType type;
public StaffType Type { get => type; set => type = value; } // property
/*
* Constructor
*/
public Staff(string name, StaffType type):base() // call parent constructor
{
this.name = name;
this.type = type;
}
abstract public void sayHere(); // abstract method
}
Object Initializer
Person person = new Person {
Name = "John Doe",
Age = 39
}; // Object Initializer
// Equal to
Person person = new Person();
person.Name = "John Doe";
person.Age = 39;
Nullable / Non-nullable reference types
// Nullable
string? name; // ignore the compiler null check with name!.Length;
// Non-nullable
string name;
Lambda expressions
(input-parameters) => expression
(input-parameters) => { <sequence-of-statements> }
Action line = () => Console.WriteLine();
Func<int, int, bool> testForEquality = (x, y) => x == y;
Property
public class Person
{
public string FirstName;
public string FirstName { get; set; }
public string FirstName { get; set; } = string.Empty;
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
public string FirstName
{
get => firstName;
set => firstName = value;
}
public string FirstName { get; private set; }
public string FullName => $"{FirstName} {LastName}";
}
Indexers
public int this[string key]
{
get { return storage.Find(key); }
set { storage.SetAt(key, value); }
}
// Multi-Dimensional Maps
public int this [double x, double y]
{
get
{
var iterations = 0;
...
Deconstruction (Tuple and Object)
// _ is a Discards
/*
* Tuple
*/
public static void Main()
{
var (_, _, _, pop1, _, pop2) = QueryCityDataForYears("New York City", 1960, 2010);
...
private static (string, double, int, int, int, int) QueryCityDataForYears(string name, int year1, int year2)
{
...
/*
* Object
*/
public Person(string fname, string mname, string lname, string cityName, string stateName)
{
...
public void Deconstruct(out string fname, out string lname, out string city, out string state)
{
fname = FirstName;
lname = LastName;
city = City;
state = State;
}
var p = new Person("John", "Quincy", "Adams", "Boston", "MA");
// Deconstruct the person object.
var (fName, _, city, _) = p;
...
Generic
// Declare the generic class.
public class Generic<T>
{
public T Field;
}
public static void Main()
{
Generic<string> g = new Generic<string>();
g.Field = "A string";
//...
Console.WriteLine("Generic.Field = \"{0}\"", g.Field);
Console.WriteLine("Generic.Field.GetType() = {0}", g.Field.GetType().FullName);
}
💖 💪 🙅 🚩
Steve Mak
Posted on May 13, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.