Post

Cool C# Features

ValueTuple to swap values

1
2
3
4
5
6
7
8
9
int[] arr = new int[] { 1, 2 };

// Old fashioned technique
int temp = arr[0];
arr[0] = arr[1];
arr[1] = temp;

// Classy way to do it
(arr[0], arr[1]) = (arr[1], arr[0]);

Use discard _ variable for unused variables

1
2
3
4
5
6
7
8
// Returns true if hit something
private bool CollisionDetection(out object hitObject)
{
  // ...
}

// Just interested whether collision occured or not
bool collisionOccured = CollisionDetection(out _);

Use ValueTuple instead of multiple out declared method parameters

1
2
3
4
5
6
7
8
9
10
private void Foo(out int value1, out int value2)
{
  // ...
}

// ValueTuple solution
private (int value1, int value2) Foo()
{
  // ...
}

Use switch expression to save some lines and improve readability

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// The old, boring switch statement implementation
string response;
switch (message)
{
    case "Hey!":
    {
        response = "Hi!";
    } break;
    case "Goodbye!":
    {
        response = "See you later!";
    } break;
    default:
    {
        response = string.Empty;
    } break;
}

// Much compact and good looking switch expression implementation
string response = message switch
{
    "Hey!" => "Hi!",
    "Goodbye!" => "See you later!",
    _ => string.Empty
};

These are the ones I can think of right now, I may add new ones in the future.

This post is licensed under CC BY 4.0 by the author.