Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the return _ in C#

Tags:

c#

asp.net

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.

like image 459
Edward Cooke Avatar asked Aug 29 '15 20:08

Edward Cooke


2 Answers

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 =>?

like image 98
lintmouse Avatar answered Oct 18 '22 05:10

lintmouse


_ 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

like image 42
Eduardo Wada Avatar answered Oct 18 '22 06:10

Eduardo Wada