8

I have a question on something I've never seen before in C#. In the service provider in the new asp.net dependency injection, there is a method with return _ => null;

https://github.com/aspnet/DependencyInjection/blob/dev/src/Microsoft.Framework.DependencyInjection/ServiceProvider.cs Lines 63-72.

The method in question:

private Func<MyServiceProvider, object> CreateServiceAccessor(Type serviceType)
{
    var callSite = GetServiceCallSite(serviceType, new HashSet<Type>());
    if (callSite != null)
    {
        return RealizeService(_table, serviceType, callSite);
    }
    return _ => null;
}

What is the _ ? Is it new in C# 6? Searching around for return _ doesn't return anything useful, unless you want naming conventions.

jv42
  • 8,521
  • 5
  • 40
  • 64

3 Answers3

6

If you are not using the parameter in a lambda, people use _ as a convention for indicating that.

In your code, it is the catchall case for if serviceType isn't resolved to a call site. Since you don't care about the serviceType to return null, _ is used for that parameter.

This is probably a duplicate of this post which has lots of info:

C# style: Lambdas, _ => or x =>?

Community
  • 1
  • 1
lintmouse
  • 5,079
  • 8
  • 38
  • 54
  • Thanks for the link with more details. It makes sense now, just a variable name. I was thinking it had some special meaning because that's the first time I've seen an underscore used by itself like that. – Edward Cooke Aug 29 '15 at 20:48
2

_ is a valid C# identifier, so _ => null is the same as myServiceProvider => null

Defining what is a valid identifier is not as simple as checking the characters for a white list of allowed characters, but it's documented here

Eduardo Wada
  • 2,606
  • 19
  • 31
0

For C#7 onwards, the language (or rather the compiler) recognizes the convention that a single _ denotes an unimportant value: https://learn.microsoft.com/en-us/dotnet/csharp/discards

Starting with C# 7.0, C# supports discards, which are temporary, dummy variables that are intentionally unused in application code. Discards are equivalent to unassigned variables; they do not have a value. Because there is only a single discard variable, and that variable may not even be allocated storage, discards can reduce memory allocations. Because they make the intent of your code clear, they enhance its readability and maintainability.

You indicate that a variable is a discard by assigning it the underscore (_) as its name.

Community
  • 1
  • 1
Hans Kesting
  • 38,117
  • 9
  • 79
  • 111