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 object _);

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()
{
  // ...
}

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

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