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

Time:01-23

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.

CodePudding user response:

As mentioned in the other answers, 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 (i.e. have the property retuning 100) will be used.
This is called default interface implementation and it is available from C# 8.0 only.

CodePudding user response:

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

CodePudding user response:

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.

  • Related