dotnet / aspnetcore

ASP.NET Core is a cross-platform .NET framework for building modern cloud-based web applications on Windows, Mac, or Linux.
https://asp.net
MIT License
35.59k stars 10.06k forks source link

Passing object as parameter to component fails with implicit operator #5632

Closed tidyui closed 2 years ago

tidyui commented 6 years ago

Consider the following code:

namespace MyModels
{
    public interface IField 
    {
        Guid Id { get; set; }
    }

    public class StringField : IField
    {
        public Guid Id { get; set; }
        public string Value { get; set; }

        public static implicit operator string(StringField field)
        {
            return field.Value;
        }
    }
}

I have a component for rendering a StringField in the UI that simplified looks like this:

<input type="text" bind="@Data.Value" />

@functions {
    [Parameter]
    private MyModels.StringField Data { get; set; }
}

In my main page I operate on a collection of IField objects. Trying to invoke the component like this fails as runtime. This has worked fine for all previous components that didn't have the implicit operator.

<StringField Data="@((MyModels.StringField)Field)"></StringField>

However changing the component to this and passing the param as an IField works just fine but is a bit messy.

<input type="text" bind="@(((MyModels.StringField)Data).Value)" />

@functions {
    [Parameter]
    private MyModels.IField Data { get; set; }
}

It looks like the implicit operator converts the param before trying to set it in runtime making the app break.

tidyui commented 6 years ago

I've created a test repository here https://github.com/tidyui/BlazorBindingTest that shows the three scenarios:

  1. StringField failing with implicit op /fieldfails
  2. StringField works without implicit op /fieldworks
  3. StringField works with implicit op when passed as interface /fieldbyinterface
danroth27 commented 6 years ago

@SteveSandersonMS This seems to happen pretty deep in how parameters get handled.

mkArtakMSFT commented 2 years ago

Closing this as a dupe of https://github.com/dotnet/aspnetcore/issues/18042