Error cs0236 a field initializer cannot reference the non static field method or property

I don't understand this error in C# error CS0236: A field initializer cannot reference the non-static field, method, or property 'Prv.DB.getUserName(long)' For the following code public class

Asked
13 years, 8 months ago

Viewed
17k times

I don’t understand this error in C#

error CS0236: A field initializer cannot reference the non-static field, method, or property ‘Prv.DB.getUserName(long)’

For the following code

public class MyDictionary<K, V>
{
    public delegate V NonExistentKey(K k);
    NonExistentKey nonExistentKey;

    public MyDictionary(NonExistentKey nonExistentKey_) { }
}

class DB
{
    SQLiteConnection connection;
    SQLiteCommand command;

    MyDictionary<long, string> usernameDict = new MyDictionary<long, string>(getUserName);

    string getUserName(long userId) { }
}

Anthony Mastrean's user avatar

asked May 28, 2009 at 21:39

1

Any object initializer used outside a constructor has to refer to static members, as the instance hasn’t been constructed until the constructor is run, and direct variable initialization conceptually happens before any constructor is run. getUserName is an instance method, but the containing instance isn’t available.

To fix it, try putting the usernameDict initializer inside a constructor.

answered May 28, 2009 at 21:42

thecoop's user avatar

thecoopthecoop

44.8k19 gold badges130 silver badges186 bronze badges

answered May 28, 2009 at 22:40

Rene's user avatar

ReneRene

2,0952 gold badges15 silver badges14 bronze badges

1

getUserName is an instance method.
Change it to static, that might work.

OR

Initialize the dictionary in the constructor.

answered May 28, 2009 at 21:42

shahkalpesh's user avatar

shahkalpeshshahkalpesh

32.9k3 gold badges66 silver badges87 bronze badges

You cannot do this because the instance has to be initialized before you can access the properties of its class. The field initializers are called before the class is initialized.

If you want to initialize the field usernameDict with the return-value of the GetUserName-Method you have to do it within the constructor or make the Method a static one.

answered May 28, 2009 at 21:47

zoidbeck's user avatar

zoidbeckzoidbeck

4,0611 gold badge25 silver badges25 bronze badges

Permalink

Cannot retrieve contributors at this time

description title ms.date f1_keywords helpviewer_keywords

Compiler Error CS0236

Compiler Error CS0236

06/26/2021

CS0236

CS0236

Compiler Error CS0236

A field initializer cannot reference the non-static field, method, or property ‘name’.

Instance fields cannot be used to initialize other instance fields outside a method.

To correct this error

If you are trying to initialize a variable outside a method, consider performing the initialization inside the class constructor. For more information, see Methods.

Example

The following sample generates CS0236, and shows how to fix it:

public class MyClass
{
    public int i = 5;

    // To fix the error, remove "= i", and uncomment the line in constructor.
    public int j = i;  // CS0236

    public MyClass()
    {
        // Uncomment the following.
        //j = i;
    }
}

C# Compiler Error

CS0236 – A field initializer cannot reference the non-static field, method, or property ‘name’

Reason for the Error

You will receive this error in your C# program when you are trying to initialize a member or variable using other instance fields outside of method.

For example, try to compile the below code snippet.

namespace DeveloperPubNamespace
{
    public class Employee
    {
        public string SurName = "";
        public string LastName = SurName;

    }
    class Program
    {
        public static void Main()
        {
        }
    }
}

This program will result with the C# error code CS0236 because the instance field LastName is initialized directly (outside of method) using another instance field SurName.

Error CS0236 A field initializer cannot reference the non-static field, method, or property ‘Employee.SurName’ DeveloperPublish C:UsersSenthilBalusourcereposConsoleApp3ConsoleApp3Program.cs 6 Active

C# Error CS0236 – A field initializer cannot reference the non-static field, method, or property 'name'

Solution

To fix the error code CS0236 in C#, you should consider initializing the field either inside a method or using the class’s constructor.

namespace DeveloperPubNamespace
{
    public class Employee
    {
        public string SurName = "";
        public string LastName;
        public Employee()
        {
            LastName = SurName;
        }

    }
    class Program
    {
        public static void Main()
        {
        }
    }
}

В чём проблема?
Вроде бы всё правильно,но оно мне пишет

Assets/Scripts/moving.cs(9,23): error CS0236: A field initializer cannot reference the nonstatic field, method, or property `moving.obj'

и

Assets/Scripts/moving.cs(8,23): error CS0236: A field initializer cannot reference the nonstatic field, method, or property `moving.obj'

ошибка,та же что там,что там.
Bот мой код:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class moving : MonoBehaviour {
	public GameObject obj;
	private float speed = 5f;
	private float xPos = obj.transform.position.x;
	private float yPos = obj.transform.position.y;

	private void Update () {
		if (Input.GetKey (KeyCode.D)) {
			xPos = xPos + speed * Time.deltaTime;
		} else if (Input.GetKey (KeyCode.W)) {
			yPos = yPos + speed * Time.deltaTime;
		} else if (Input.GetKey (KeyCode.A)) {
			xPos = xPos - speed * Time.deltaTime;
		} else if (Input.GetKey (KeyCode.S)) {
			yPos = yPos - speed * Time.deltaTime;
		}
		obj.transform.position = new Vector3 (xPos, yPos,0);
	}
}

  • Remove From My Forums
  • Question

  • User-456111751 posted

    Hi All,

    Please review my code, i’ve removed the most part of the code which is not relevant to this:

    namespace MyQuiz
    {
        public partial class QuizPage : System.Web.UI.Page
        {
    
            protected int[] idquestion = new int[totalQuestions];
            
    
            public QuizPage()
            {
                Page.Init += new System.EventHandler(Page_Init);
    
            }
            
            
            
    
            
            private void ReadQuestionsIntoTable()
            {
                
                IEnumerable questions = SelectRows("Select * From Questions WHERE QuizID='48'");
    
                //Ashiq Code
                int a = 0;
                foreach (DataRowView question in questions)
                {
                    a++;
                }
                totalQuestions = a;
                
                foreach (DataRowView question in questions)
                {
                    
                    idquestion = new int[totalQuestions];
                    idquestion[NumberOfQuestions] = Convert.ToInt16(question["QuestionID"].ToString());
                    
                    }
    
                    
                }
            
    
            
    
            protected void Page_Load(object sender, System.EventArgs e)
            {
                if (!IsPostBack)
                {
    
                    ReadQuestionsIntoTable();
    
    
    
                }
    
                else
                {
                    bool AreAllAnswered = CalculateScore(r);
    
                }
            }
        
    
           
    
            private bool CalculateScore(HttpRequest r)
            {
              
                for (int i = 0; i < r.Form.Keys.Count; i++)
                {
                                    if (nextKey.Substring(0, 5) == "Group")
                    {
                        foreach (int ie in idquestion)
                        {
                        }
    
                        
                    }
                }
    
                return true;
            }
        }
    }
    

    What i would like to achieve from the above code is, I would like to read the value of the stored (In the method ReadQuestionsIntoTable) array
    idquestion in private bool CalculateScore(HttpRequest r).

    I’ve declared it by protected int[] idquestion = new int[totalQuestions]; initially so that i can use the array globally. I get the error message: CS0236: A field initializer cannot reference the nonstatic field, method, or property ‘MyQuiz.QuizPage.totalQuestions’

    Please help guys, I am not sure whether i am Doing correct. I got stuck with this. My intent is to use the array
    idquestion in method private bool CalculateScore(HttpRequest r) for a calculation.

Answers

  • User277293199 posted

    as the Http is stateless so any variable declared globally will lose its value during postback, so in order to keep the values in the idquestion array you would store them in the ViewState or Session objects, so that you can retrieve them after postback

    ex:

    Public int[] IdQuestionsProperty

    {

    get{return ViewState[«idQuestion»];

    set{ViewState[«idQuestion»]=value;}

    }

    please mark as an answer if it was helpful

    • Marked as answer by

      Thursday, October 7, 2021 12:00 AM

  • User-456111751 posted

    Hi Devan,

    I changed as per yours still it dint work (Same error). I did store the values to session and retrived it later as adviced by Ahmed.

    Referred the post http://forums.asp.net/t/1307299.aspx which helped a lot.

    Thanks all for ur help. 

    • Marked as answer by
      Anonymous
      Thursday, October 7, 2021 12:00 AM

Понравилась статья? Поделить с друзьями:
  • Error css class
  • Error csrf token mismatch
  • Error csrf token has expired
  • Error cs9010 primary constructor body is not allowed
  • Error cs8803 top level statements must precede namespace and type declarations