tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

C#’s discards don’t need var

23 Jan 2019 C#

From the “Today I found out and it’s even in the documentation” series. Did you know that when you’re using discards in C# (the _) you don’t have to use var? Let’s see it in action.

A simple example would be.

_ = SomeFunction();

Which of course is retarded. Most of the time. Because if you don’t care about the result, you can just call the function and not do any assignments. But there’s (at least) one reasonable example. Let’s assume you have something like this.

static async Task Main(string[] args)
{
	SomeFunctionAsync();
}

On the SomeFunctionAsync call you’ll get a CS4014 warning saying Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.. That’s mostly helpful warning, but sometimes you really want to do fire-and-forget (and you know what you’re doing). Although there’s multiple way to get that warning solved, one simple is assigning to a discard (Another approach can be found here with the NoWarning method.).

static async Task Main(string[] args)
{
	_ = SomeFunctionAsync();
}

And I find this very clean and expressive, because in my mind it can’t be considered an overlook.

But back to the topic. More reasonable usage is with out variables, where you sometimes don’t care about one or few. So instead of writing.

bool IsInt(string s) => int.TryParse(s, out var _);

You can write.

bool IsInt(string s) => int.TryParse(s, out _);

Which obviously is shorter and more succinct. And I like succinct code.

Now I have to go through all of my code, change it and pretend I knew from beginning. 😉

Profile Picture Jiří Činčura is an independent developer focusing on data and business layers, language constructs, parallelism and databases. Specifically Entity Framework, asynchronous and parallel programming, cloud and Azure. He's Microsoft Most Valuable Professional and you can read his articles, guides, tips and tricks at www.tabsoverspaces.com.