Skip to content

Assigning an object with implicit operator (cast to string) to Blazor component's parameter causes InvalidCastException #18042

@Oblomoff

Description

@Oblomoff

Object

namespace BlazorBug
{
    public class Tag
    {
        public Tag(string value) => Value = value;

        public string Value { get; }

        /*
         * BUG!
         * 
         * This implicit operator causes InvalidCastException:
         * Unable to cast object of type 'System.String' to type 'BlazorBug.Tag'.
         * 
         * Comment the code below to avoid the exception.
         */
        public static implicit operator string(Tag tag) => tag.Value;
    }
}

Component

<h3>Tag Editor</h3>

<p>@Tag</p>

@code {
    [Parameter]
    public Tag Tag { get; set; }
}

Assignment

@page "/"

<TagEditor Tag="Tag" />

@code {
    public Tag Tag { get; } = new Tag("My Tag");
}

Exception

InvalidCastException: Unable to cast object of type 'System.String'
to type 'BlazorBug.Tag'.

InvalidOperationException: Unable to set property 'Tag' on object of type
'BlazorBug.Shared.TagEditor'. The error was: Unable to cast object of type
'System.String' to type 'BlazorBug.Tag'.

Sample project

BlazorBug.zip

Metadata

Metadata

Assignees

Labels

affected-very-fewThis issue impacts very few customersarea-blazorIncludes: Blazor, Razor ComponentsbugThis issue describes a behavior which is not expected - a bug.feature-blazor-component-modelAny feature that affects the component model for Blazor (Parameters, Rendering, Lifecycle, etc)severity-blockingThis label is used by an internal tool

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions