Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading