MattHodson
MattHodson

Reputation: 796

Calling a class with Blazor failing "a field initializer cannot reference the nonstatic field, method, or property"

I'm just getting started in Blazor from Web Forms, & I'm very impressed. However, I'm struggling to figure out what my problem is here when calling a class in Blazor.

Trying to call the call like this:

@code {
testingClass t = new testingClass();
string Teststring = t.TestResponse();
}

The class in question:

 namespace BlazorTesting.Data
  {
    public class testingClass
    {
        public string TestResponse()
        {
            return "hello world";
        }    
    }
}

The problem line of code & what Visual Studio says the error is:

string Teststring = t.TestResponse();
a field initializer cannot reference the nonstatic field, method, or property 'Component.t'

It should be noted, I do have @using BlazorTesting.Data on my Razor page.

Upvotes: 1

Views: 1517

Answers (2)

enet
enet

Reputation: 45764

Your issue is not specific to Blazor... You cannot initialize Teststring with a value from something that is not yet exist.

Instance fields cannot be used to initialize other instance fields outside a method. If you are trying to initialize a variable outside a method, consider performing the initialization inside the class constructor

Or a method such as the OnInitialized lifecycle method...

You can do that like this:

@code {
    testingClass t = new testingClass();
    string Teststring => t.TestResponse();

    public class testingClass
    {
        public string TestResponse()
        {
            return "hello world";
        }
    }
}

You can also do that like the code snippet below, which is the preferred way:

@code {
    // Define the variables
    testingClass t;
    string Teststring;

    protected override void OnInitialized()
    {
         // Instantiate your object 
         t = new testingClass();
         // and then use it
        Teststring = t.TestResponse();
    }

    public class testingClass
    {
        public string TestResponse()
        {
            return "hello world";
        }
    }
}

Upvotes: 2

Henk Holterman
Henk Holterman

Reputation: 273854

This is a standard C# error, not specific to Blazor.
You will have to execute TestResponse() later, OnInitialized() is a good spot.

@code 
{
  testingClass t = new testingClass();
  string Teststring;

  protected override OnInitialzied()
  {
    Teststring = t.TestResponse();
  }
}

beware of the null cases, but for a string that shouldn't be much of a problem.

Upvotes: 2

Related Questions