skip to Main Content

I understand the concept of non-nullable types, and try to use them whenever possible, but have hit a situation where I don’t understand what to do.

If I create a Blazor component (content irrelevant and therefore not shown), and want to refer to it in code, I can add a private variable for it. Since I know that Blazor will assign it a value, I can tell the compiler not to worry that it is non-nullable, but I haven’t set an initial value…

private MyComponent _myComponent = null!;

I can then use @ref in the markup, which will populate the variable with a reference to the component…

<MyComponent @ref="_myComponent" />

However, Visual Studio gives me a wavy green line under the last part of this line, and a warning "Cannot convert null literal to non-nullable reference type".

I’m not sure how to get around this. I’m not even sure what the warning means, as I told the compiler that the variable won’t be null.

Can anyone explain a) what I’m doing wrong here, and b) how I should be doing this? Thanks

2

Answers


  1. Try this:

    private CptVendor? _myComponent = null!;
    
    Login or Signup to reply.
  2. Instead of = null!;, which you (understandably) said you don’t want to use, how about…

    private MyComponent _myComponent = new();
    

    This obviously only works if the constructor doesn’t take any parameters. If it does, you’d have to add some dummy values for those. This isn’t an issue, as the framework will overwrite your value with a reference to the actual form, and it does get around your problem.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search