1

This is in a new blazor project template in visual studio.

Index.razor:

@code
{
    bool test = false;
}

Program.cs:

NewProject.Pages.Index.test = true;

This throws "an object reference is required for the non-static field, method, or property "Index.test"". But I'm not sure how to reference NewProject.Pages.Index as an object because I can't find where it is instantiated. How do I get the object reference for the page that blazor displays in the browser?

Nathan Dehnel
  • 133
  • 10
  • 1
    Program.cs is not the place for application code. In general, if you want to set a property value when your page is visited, you do that in the OnInitialized method of the page, or one of the other key lifecycle events for the page. See here for details: https://blazor-tutorial.net/lifecycle-methods. To try to put this in simple terms, your becomes an object when it is created, and that happens when someone visits the page. You refer to it in your code simply by referencing its properties and methods in the code for the page (blazor component). – topsail Jun 10 '22 at 20:24

1 Answers1

3

The @code section in a .razor file is part of the class for that component. Its properties and fields are treated the same as properties and fields of an ordinary class. The default in C# for properties and fields is internal and instance--you'd have to have an instance of the Index component. But we almost never would create references of component instances manually; the @Page routing system or parent components allow the runtime to create instances for us, so we'd never have a reference to a component instance directly.

So, if you want to access items inside the component without having an instance of the component (since you are calling it presumably from Program.Main), you'd have to mark it public static like this:

@code
{
    public static bool Test {get; set;} = false;
}

Then that single value would be available anywhere; you could access it from Program.cs via NewProject.Pages.Index.Test, as it would...but I'd question why you want to do this. Care to provide any broader context on what you are trying to do here so I can help with the "real" issue at hand here?

Patrick Szalapski
  • 8,738
  • 11
  • 67
  • 129
  • I basically have a pre-existing c# program that I am trying to convert into a blazor program without rewriting all of it. – Nathan Dehnel Jun 13 '22 at 16:11