Skip to main content
Enchanted Code

Handy C# Knowledge

tutorial, cs

Intro

Just some things I have learnt when programming in the csharp language that didn’t make for a separate tutorial.

This will be updated when I learn new cool things in C#.

Keywords

Ref (Passing values by reference)

  • A referenced local variable will not only effect the local variable but the variable from where it was passed.
int a = 5;
AddOne(ref a);
Console.WriteLine(a);

public static void AddOne(ref int a)
{
    a += 1;
}

Out (passing variable by Ref & assigning a value to it)

  • parameters are always passed by reference
  • variable must only be initialized when calling with out
  • variable can be initialized with the out keyword or outside separately
GetMyInt(out int a);
Console.Write(a);

public static void GetMyInt(out int x)
{
    x = 10;
}

Useful things

Swapping variables

Extra variable

  • requires extra variable to be defined
int a = 4;
int b = 8;

int c = a;
int a = b;
int b = c

Tuples (C# 7.0)

  • does not need extra variable defined
  • more readable
int a = 4;
int b = 8;

(a, b) = (b, a);

Compact Getters/Setters

Traditional

  • can get messy when there are lots of getters and setters
class MyClass
{
    private string myVar1 = "hello";
    public string MyVar1
    {
        get
        {
            return myVar1;
        }
    }
}

Compact 1

  • supports both get and set
class MyClassCompact
{
    private string myVar1 = "hello";
    public string MyVar1
    {
        get => myVar1;
    }
}

Compact 2

  • only supports getter
  • very clean (only uses one line)
class MyClassCompact2
{
    private string myVar1 = "hello";
    public string MyVar1 => myVar1;
}

Auto Defined Private Fields

Traditional

  • two variables are written
  • looks neater when lots of fields defined
class MyClass
{
    private string myVar1;
    public string MyVar1 => myVar1;
}

Compact

  • no need to write another variable name
  • private variable is still defined internally
  • can still set variable inside class (acts as private)
class MyClassCompact
{
    public string MyVar1 { get; private set; }
}