0

I've been trying to solve this for the past 5 hours, but couldn't find any solution - please help me solve this problem.

This is my code:

@foreach (string title in titleList)  
{
    <span> @title</span>
}

@code {
    [Parameter]
    public string theTitle { get; set; }

    public static string[] titleList { get; set; } = theTitle.Split(", "); 
}

I keep getting this error:

A field initializer cannot reference the non-static field, method, or property 'RelatedTopics.theTitle'

After I change to this:

[Parameter]
public static string theTitle { get; set; }

it still doesn't work in my application. Please help me with a solution for this.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Arjun Ghimire
  • 301
  • 1
  • 2
  • 8
  • 1
    What do you mean by still doesn't work? Are you getting the same error? – Shameel Sep 04 '22 at 14:54
  • Does this answer your question? [A field initializer cannot reference the nonstatic field, method, or property](https://stackoverflow.com/questions/14439231/a-field-initializer-cannot-reference-the-nonstatic-field-method-or-property) – Dimitris Maragkos Sep 04 '22 at 15:00
  • Have you tried `public static string[] titleList {get; set; } = theTitle?.Split(", ") ?? Array.Empty();` Maybe your parameter is empty at the beginning? – Martin Sep 04 '22 at 15:10
  • Hello Martin , After I applied this it doesn't give error but when I apply this loop it doesn't give any result = @foreach (string title in titleList) {
      @title
    }
    – Arjun Ghimire Sep 04 '22 at 15:31

1 Answers1

2

You can't use one instance variable to initialize another one using a field initializer. Instead put that code into OnParametersSet lifecycle method.

@foreach (string title in titleList)
{
    <span> @title</span>           
}

@code{
    [Parameter]
    public string theTitle { get; set; }

    private string[] titleList = Array.Empty<string>();
   
    protected override void OnParametersSet()
    {  
        if (!string.IsNullOrEmpty(theTitle))
        {
            titleList = theTitle.Split(", ");
        }
    }
}

If your string is space separated you should do theTitle.Split(" "); instead of theTitle.Split(", ");

Dimitris Maragkos
  • 8,932
  • 2
  • 8
  • 26