Member-only story
6 C# Features You Probably Didn’t Know Exist
Who would’ve thought these work.
1. Tweaking File Paths
Okay, so the first thing I found out is about file paths in C#.
You can actually use the division symbol to work with them. I tried this out, and it was surprising to see how you can kind of ‘split’ the path in your code using this symbol. It’s a bit out of the ordinary, but it’s neat to see it work.
public class FilePath
{
private string path;
public FilePath(string initialPath)
{
path = initialPath;
}
public static FilePath operator /(FilePath filePath, string addition)
{
return new FilePath(filePath.path + "/" + addition);
}
public override string ToString()
{
return path;
}
}
// Usage
var basePath = new FilePath("C:/Users/YourUser");
var fullPath = basePath / "Documents" / "test.txt";
Console.WriteLine(fullPath);
2. The ‘Await Anything’ Trick
Next, there’s this thing where you can make C# wait for just about anything. It sounds a bit weird, right? But it’s true.
By adding something called a GetAwaiter
method, you can make the code pause for anything – even a number! I gave this a go, and it was pretty wild to see the code pause just…