简体   繁体   中英

What does the part "=> 100" mean in the C# property?

In some article I found this:

public interface ICargo {
    int FoodStorage { get => 100; }
}

What does the part => 100 mean?
From the context it looks like a default value. But as I know this is not how the default value is set. At least, I've never seen this kind of syntax in this context.

I've tried googling, it didn't help.

The syntax is called expression-bodied property/member .
It can be used for a read-only propery as demonstrated by your code.

get => 100;

Is equivalent to:

get { return 100; }

But in your specific case there is another issue involved:
Since you use it in an interface, it actually provides a default implementation for the property.
If a class implementing the interface does not provide impelmentation for this property, the default provided by the interface (ie have the property retuning 100) will be used.
This is called default interface implementation and it is available from C# 8.0 only.

It's an expression bodied element basically it would behave the same as

public interface ICargo 
{ 
    int FoodStorage { get { return 100; } 
}

Making use of a lambda expression can make the code cleaner without the excess brackets. You can use both syntax wherever you can use properties.

It is expression bodies property , its short form of writing a property which has only getter and has the constant value.

Its equivalent is

public int FoodStorage
{
    get { return 100; }
}

and its read-only property, the expression-bodied property is available from C# 6.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM