What does _ in C#mean?

Asked

Viewed 201 times

18

I was servicing a system until I came across the following code:

object auth;
var authContext = HttpContext.Items.TryGetValue("SystemQueryContext", out auth);
var result = await _systemService.Metodo(auth as QueryContext);    

I made the following change:

var authContext = HttpContext.Items.TryGetValue("SystemQueryContext", out object auth);
var result = await _systemService.Metodo(auth as QueryContext);  

However, the Intellisense of Visual Studio offered me the following change:

_ = HttpContext.Items.TryGetValue("SystemQueryContext", out object auth);
var result = await _systemService.Metodo(auth as QueryContext); 

I’ve never seen this _ being used, I tried to use it as variable and is not possible, so I would like to understand about this feature, in which cases can be used, what it does?

1 answer

17


It is a way to indicate that you do not want to use any value. It’s like a fictitious variable (but not a real one so you can’t use it), so you’re saying explicitly that you know that a value is being received by the method being called and that you want that value to be dropped, so this is a language construct called discard which was recently introduced in C# 7.

In fact this called method is part of a dictionary and returns a boolean as per documentation. The return is whether the operation went well or not, so you should do something then conditionally, if it went wrong the object obtained in the out is invalid and should not be used, if there is no error of face. Even Visual Studio indicating to do this I would use it in a if and would not use the discard, after all VS did not see the whole context, he only understood that since he is creating a variable and is not using it, why not discard the value and stop creating the useless variable?

Obviously this same symbol can be used in a variable name as any character (as long as the name is not only this character), but this is not what you want to know, it is not idiomatic in C# to use it anyway, never was, ie vice of other languages, _systemService it won’t hurt at all, but every time I see it it feels like it’s not C#.

  • The idea was just to get to if but I hit enter without reading :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.