Roslyn: Type to generate not inferred in expression bodied getter

Created on 20 May 2018  路  7Comments  路  Source: dotnet/roslyn

```c#
class C
{
int P
{
get => newField;
}
}

Generate field on `newField` creates it with type `object` (which of course results in an error):
```c#
class C
{
    private object newField;

    int P
    {
        get => newField;
    }
}

The type should be int as is correctly generated when using an expression bodied property or a block with a return statement instead.

Area-IDE Resolution-Fixed

All 7 comments

Nice find! This situation is currently not handled in the type interference service. I'm working on a fix for this, should be done later today. I'll also make sure it can handle an expression bodied setter.

@rik-smeets I don't think setters should be handled because they are void-returning unlike getters. It should be possible to just get the method symbol of the accessor and get its return type (which will only be int for the getter). The generated code would be invalid anyway.

Just like event accessors (add, remove) are void returning and generate object.

You're right, it should only generate as an int (in this example) if you do it like:

int P
{
     set => newField = value;
}

Otherwise, it should just generate an object (both already working as expected, it's the same in properties without expression bodied setters, so nothing needs to be done there). Thanks for clarifying!

Yes, set => newField = value; should definitely create int. Here it should be inferred from the type of value, not the return type of the setter. Even though that already works, please make sure you add a test for that too (if there isn't one) to prevent any regressions.

That is similar to set => newField = "hello"; - the field will be generated of type string, regardless of the type of the property itself.

As said in the linked pull request by @Neme12, this issue also occurs in expression bodied local function:

public int Y()
{
    return Foo();

    int Foo() => y;
}

Results in:

private object y;

public int Y()
{
    return Foo();

    int Foo() => y;
}

Generating methods from within these expression bodied getters or local functions has the same issue. The linked pull request resolves all this.

@jcouv @jinujoseph Can somebody close this please? The PR was merged: #26997

Was this page helpful?
0 / 5 - 0 ratings