Search code examples
c#razorblazorblazor-webassemblynullable

Compilation error with nullable parameter in Razor markup


I declared a Razor page with an optional parameter:

[Parameter]
public KeyValuePair<string, T>? Value { get; set; }

Which I use in the Razor page markup:

@if (Value != null && item.Key == Value.Key)
{
    <span>
       .....
    </span>
}

Visual Studio complains with the nullable type declared with "?" (if I remove the "?", there's no error):

CS1061  'KeyValuePair<string, T>?' does not contain a definition for 'Key' and no accessible extension method 'Key' accepting a first argument of type 'KeyValuePair<string, T>?'

It seems that it ignores my "Value != null" test. What's the "Blazor" way to fix this error?


Solution

  • KeyValuePair<K,V> is a valuetype (struct).

    When you use a nullable valuetype then you will have to deal with the Value property:

    public KeyValuePair<string, T>? Value { get; set; } 
    
    
       @if (Value != null && item.Key == Value.Value.Key)