Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "Property where class => someFunction" mean in C#

Tags:

c#

I'm browsing through the EF7 code on Github and found a line that looks like this:

public virtual DbSet<TEntity> Set<TEntity>() where TEntity : class => _setInitializer.Value.CreateSet<TEntity>(this);

I have seen that syntax before on a class level, like this:

public class SomeClass<T> where T : class

Which says that T should be of type class. But the line from the EF7 source confuses me. I'm not sure what it does.

like image 801
Vivendi Avatar asked Dec 15 '15 08:12

Vivendi


3 Answers

It's an expression-bodied member, a new syntax in C# 6.

It's a method, not a property. C# doesn't allow generic properties.

It's the same as

public virtual DbSet<TEntity> Set<TEntity>() where TEntity : class
{
    return _setInitializer.Value.CreateSet<TEntity>(this);
}
like image 53
Jakub Lortz Avatar answered Oct 05 '22 05:10

Jakub Lortz


This syntax is a bit confusing indeed, but actually the lambda construct here has nothing to do with generic constraints. It's just an Expression-Bodied Method that happened to have a generic constraint.

You can think of it as:

public virtual DbSet<TEntity> Set<TEntity>() where TEntity : class
{
    return _setInitializer.Value.CreateSet<TEntity>(this);
}

See Roslyn Wiki

like image 45
haim770 Avatar answered Oct 05 '22 07:10

haim770


It's a C# 6.0 feature called Expression Bodied Method.

Read here about it.

The code is equivalent to:

public virtual DbSet<TEntity> Set<TEntity>() where TEntity : class 
{
    return _setInitializer.Value.CreateSet<TEntity>(this);
}
like image 32
Amir Popovich Avatar answered Oct 05 '22 05:10

Amir Popovich