-1

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.

wohlstad
  • 12,661
  • 10
  • 26
  • 39
kozavr
  • 9
  • 1
  • It's a special syntax for implementing properties. It just means the property `get` method will return `100`. Since in your case it is in an interface, it will actual serve as a default implementation (in case the class implementing the interface is not supplying an implementation). Note that default interface implementation is available from C# 8.0 only. – wohlstad Jan 22 '23 at 12:27
  • Does this answer your question? [What does the => operator mean in a property or method?](https://stackoverflow.com/questions/31764532/what-does-the-operator-mean-in-a-property-or-method) – Martin Smith Jan 22 '23 at 12:47
  • @wohlstad - hmm, maybe not a dupe then given the wrinkle about "default interface implementation" - what do you think? In any event if not a dupe your comment should be an answer – Martin Smith Jan 22 '23 at 12:55
  • @MartinSmith I'm not sure. On the one hand this case is a bit different because of the interface. On the other hand the OP is mainly interested in this special syntax which is the same for "normal" class properties. – wohlstad Jan 22 '23 at 13:01
  • 1
    @MartinSmith added an answer based on my comment. – wohlstad Jan 22 '23 at 13:57

3 Answers3

2

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.

wohlstad
  • 12,661
  • 10
  • 26
  • 39
1

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
1

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

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197