Skip to content

Wrong inferred type param when passing this to Microsoft.JSInterop.DotNetObjectRef #12446

Closed
@chucker

Description

@chucker

Preview 6 replaces DotNetObjectRef with a generic DotNetObjectRef<T>. Instead of a constructor, the Create<T> method is now used.

When passing this from within a component, this leads to unexpected results due to Razor's parsing behavior.

To Reproduce

Steps to reproduce the behavior:

  1. Using ASP.NET Core 3.0 Preview 6 and Visual Studio 2019 16.2 Preview 4
  2. Create a new Blazor component MySampleComponent.razor
  3. Place this code inside its @code section:
    private DotNetObjectRef<MySampleComponent> _Instance;

    protected override async Task OnAfterRenderAsync()
    {
        _Instance = DotNetObjectRef.Create(this);
    }
  1. See error

Expected behavior

This should compile. The type parameter of Create<T> should be inferred as MySampleComponent.

Actual behavior

This doesn't work, because Razor internally renames your class to __generated__MySampleComponent. Consequently, the Error List will show:

CS0029 Cannot implicitly convert type Microsoft.JSInterop.DotNetObjectRef<__generated__MySampleComponent> to Microsoft.JSInterop.DotNetObjectRef<MySampleComponent>

If you explicitly specify the type parameter, the error changes to CS1503.

Workaround

You can declare the variable with the generated class name:

    private DotNetObjectRef<__generated__MySampleComponent> _Instance;

    protected override async Task OnAfterRenderAsync()
    {
        _Instance = DotNetObjectRef.Create(this);
    }

However, this is presumably not the intended behavior.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions