Home > Software engineering >  Pattern matching tuples with "is" keyword?
Pattern matching tuples with "is" keyword?

Time:11-22

I have a Blazor service which accepts any draggable object, boxed as object. It could be a dragged user, or a classroom, or a scheduled item or almost anything else I might dream up later.

When the draggable is dropped into any component which supports dropping, the component needs to check if it's the right kind of object. For example, the StudentList.razor component will only accept drops if they are IdentityUser or the duple (IdentityUser, string) where the string might be a role name or some other arbitrary info (TBD later):

    <div  @ondrop="_=>HandleStudentDrop()">
       . . .
    </div>
    @code {
        async Task HandleStudentDrop()
        {
            if (DM.GetItem() is IdentityUser Person)
            {           
                // Do generic user thing (works fine)
             
            } 
            if (DM.GetItem() is (IdentityUser person,string  role) RolePerson)
            {
                // Do thing based on specified role
                // Error (active)   CS1061  'object' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'object' could be found
            }
        }
    }

I can pattern-check a class instance like IdentityUser, but I can't figure out how to check if the boxed object fits a particular duple form.

My question: what's the right syntax (if any) to check the signature of a duple using the 'is' keyword?

I've seen examples with pattern-matching duples with values using switch, but I really just want to check if the boxed object is an `(IdentityUser, string) duple.

My references:

enter image description here

In your case, it'd be:

async Task HandleStudentDrop()
{
    if (DM.GetItem() is IdentityUser Person)
    {           
        // Do generic user thing (works fine)
             
    } 
    else if (DM.GetItem().IsTuple( out ( IdentityUser person, String role )? ok ) )
    {
        <p><b>Name:</b> @( ok.Value.person.Name )</p>
        <p><b>Role:</b> @( ok.Value.role )</p>
    }
}
  • Related