DEV Community

Steve Mak
Steve Mak

Posted on • Updated on

Cheatsheet for C#*

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
Enter fullscreen mode Exit fullscreen mode

Modifier

abstract async await const event
extern in new out override
readonly sealed static unsafe virtual
volatile
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

Null Conditional Operator (?.)

PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(FirstName)));
Enter fullscreen mode Exit fullscreen mode

Enums

public enum CarType
{
    Toyota = 1,
    Honda = 2,
    Ford = 3,
}

CarType myCarType = CarType.Toyota;
Enter fullscreen mode Exit fullscreen mode

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})";
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 } };
Enter fullscreen mode Exit fullscreen mode

Lists

List<int> numbers = new List<int>();
int[] array = new int[] { 1, 2, 3 };
numbers.AddRange(array);
Enter fullscreen mode Exit fullscreen mode

Dictionaries

Dictionary<string, long> phonebook = new Dictionary<string, long>();
phonebook.Add("Alex", 4154346543);
phonebook["Jessica"] = 4159484588;
Enter fullscreen mode Exit fullscreen mode

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++;
}
Enter fullscreen mode Exit fullscreen mode

Methods

public static int Multiply(int a, int b)
{
    return a * b;
}
Enter fullscreen mode Exit fullscreen mode

Interface

interface ISkills
{
    void language();
    void sport();
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

Nullable / Non-nullable reference types

// Nullable
string? name; // ignore the compiler null check with name!.Length;

// Non-nullable
string name;
Enter fullscreen mode Exit fullscreen mode

Lambda expressions

(input-parameters) => expression
(input-parameters) => { <sequence-of-statements> }
Action line = () => Console.WriteLine();
Func<int, int, bool> testForEquality = (x, y) => x == y;
Enter fullscreen mode Exit fullscreen mode

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}";
}
Enter fullscreen mode Exit fullscreen mode

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;
...
Enter fullscreen mode Exit fullscreen mode

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;
...
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)