Enchanted Code

Handy C# Knowledge

2 minutes read

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.
1
2
3
4
5
6
7
8
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
1
2
3
4
5
6
7
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
1
2
3
4
5
6
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
1
2
3
4
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
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class MyClass
{
    private string myVar1 = "hello";
    public string MyVar1
    {
        get
        {
            return myVar1;
        }
    }
}

Compact 1

  • supports both get and set
1
2
3
4
5
6
7
8
class MyClassCompact
{
    private string myVar1 = "hello";
    public string MyVar1
    {
        get => myVar1;
    }
}

Compact 2

  • only supports getter
  • very clean (only uses one line)
1
2
3
4
5
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
1
2
3
4
5
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)
1
2
3
4
class MyClassCompact
{
    public string MyVar1 { get; private set; }
}

See Also

Buy Me A Coffee