Luxx
Luxx

Reputation: 23

Blazor: name does not exist in current context

I am receiving an error of CS0103 - 'The name 'newHotel' does not exist in the current context':

I've created a class called 'Hotel', and a property called 'HotelName'.
I've created a variable called 'newHotel', which is of type Hotel.
And I have initialised the variable with a value of "Paradise Beach".

@page "/hotels"


<h3>Hotels</h3>
<p>
    Hotel Name: @newHotel.HotelName // **THIS IS WHERE THE ERROR IS SHOWN IN VS2019**
</p>

Remaining code:

@code {

    protected override void OnInitialized()
    {
        base.OnInitialized();

        Hotel newHotel = new Hotel 
        {
            HotelName = "Paradise Beach"
        };
    }

    class Hotel
    {
        public string HotelName { get; set; }
    }
}

I can't tell where I am going wrong?

Many thanks,

Upvotes: 2

Views: 10188

Answers (2)

Gerhard Klopper
Gerhard Klopper

Reputation: 11

I don't know if this has been resolved or not. For me, deleting the '.vs' folder did the trick. I don't actually think it's something in the code. It might be that Visual Studio acts up after updating to new versions.

Upvotes: 1

Wayne Davis
Wayne Davis

Reputation: 424

It is because newHotel is a local variable declared in the OnInit method so it is out of scope. Add a property above the OnInitialized method for newHotel.


@code {

    ///Added property
    Hotel newHotel { get; set; } = new Hotel();

    protected override void OnInitialized()
    {
        base.OnInitialized();

        newHotel = new Hotel 
        {
            HotelName = "Paradise Beach"
        };
    }

    class Hotel
    {
        public string HotelName { get; set; }
    }
}

Edit: The next issue you will encounter is a NullReference error for newHotel due to the page trying to render before the OnInit method runs and newHotel is initialized. One option is to add a null check for newHotel another option is to initialize it when it is being declared.


@page "/hotels"


<h3>Hotels</h3>

@if(newHotel != null)
{
<p>
    Hotel Name: @newHotel.HotelName
</p>
}

Upvotes: 4

Related Questions