Ошибка компилятора cs0236

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;
    }
}

В классе создал array, состоящий из объектов GameObject. Затем при попытке создания переменной blocksAmount она подсвечивается красным и выдает ошибку:

CS0236 : A field initializer cannot reference the nonstatic field, method, or property 'Ball.initialBlocksAmount'

Ниже код.

public class Ball : MonoBehaviour
{

    [SerializeField] GameObject[] initialBlocksAmount = UnityEngine.GameObject.FindGameObjectsWithTag("block");
    
    int blocksAmount = initialBlocksAmount.Length;

Помогите, пожалуйста, понять ошибку.

aleksandr barakin's user avatar

задан 19 мар 2021 в 8:12

faritowich's user avatar

1

Количество можно получить только внутри какого-либо метода, например

int blocksAmount;

public void Start() {
    blocksAmount = initialBlocksAmount.Length;        
}

До компиляции, до запуска игры, до создания объекта, компилятор ничего не знает об initialBlocksAmount и не может просчитать никакие длины. Потому что это просто класс, черновик, набросок

ответ дан 19 мар 2021 в 8:19

Алексей Шиманский's user avatar

Алексей ШиманскийАлексей Шиманский

72.3k11 золотых знаков87 серебряных знаков173 бронзовых знака

I have a class and when I try to use it in another class I receive the error below.

using System;
using System.Collections.Generic;
using System.Linq;

namespace MySite
{
    public class Reminders
    {
        public Dictionary<TimeSpan, string> TimeSpanText { get; set; }

        // We are setting the default values using the Costructor
        public Reminders()
        {
            TimeSpanText.Add(TimeSpan.Zero, "None");
            TimeSpanText.Add(new TimeSpan(0, 0, 5, 0), "5 minutes before");
            TimeSpanText.Add(new TimeSpan(0, 0, 15, 0), "15 minutes before");
            TimeSpanText.Add(new TimeSpan(0, 0, 30, 0), "30 minutes before");
            TimeSpanText.Add(new TimeSpan(0, 1, 0, 0), "1 hour before");
            TimeSpanText.Add(new TimeSpan(0, 2, 0, 0), "2 hours before");
            TimeSpanText.Add(new TimeSpan(1, 0, 0, 0), "1 day before");
            TimeSpanText.Add(new TimeSpan(2, 0, 0, 0), "2 day before");
        }

    }
}

Using the class in another class

class SomeOtherClass
{  
    private Reminders reminder = new Reminders();
    // error happens on this line:
    private dynamic defaultReminder = reminder.TimeSpanText[TimeSpan.FromMinutes(15)]; 
    ....

Error (CS0236):

A field initializer cannot reference the nonstatic field, method, or property

Why does it happen and how to fix it?

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()
        {
        }
    }
}

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

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;
    }
}

I have a class and when I try to use it in another class I receive the error below.

using System;
using System.Collections.Generic;
using System.Linq;

namespace MySite
{
    public class Reminders
    {
        public Dictionary<TimeSpan, string> TimeSpanText { get; set; }

        // We are setting the default values using the Costructor
        public Reminders()
        {
            TimeSpanText.Add(TimeSpan.Zero, "None");
            TimeSpanText.Add(new TimeSpan(0, 0, 5, 0), "5 minutes before");
            TimeSpanText.Add(new TimeSpan(0, 0, 15, 0), "15 minutes before");
            TimeSpanText.Add(new TimeSpan(0, 0, 30, 0), "30 minutes before");
            TimeSpanText.Add(new TimeSpan(0, 1, 0, 0), "1 hour before");
            TimeSpanText.Add(new TimeSpan(0, 2, 0, 0), "2 hours before");
            TimeSpanText.Add(new TimeSpan(1, 0, 0, 0), "1 day before");
            TimeSpanText.Add(new TimeSpan(2, 0, 0, 0), "2 day before");
        }

    }
}

Using the class in another class

class SomeOtherClass
{  
    private Reminders reminder = new Reminders();
    // error happens on this line:
    private dynamic defaultReminder = reminder.TimeSpanText[TimeSpan.FromMinutes(15)]; 
    ....

Error (CS0236):

A field initializer cannot reference the nonstatic field, method, or property

Why does it happen and how to fix it?

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

  • User132265221 posted

    Compiler Error Message: CS0236: A field initializer cannot reference the non-static field, method, or property ‘add_contact2.db’

    Source Error:

    Line 15: {
    Line 16:     string db = HttpContext.Current.Server.MapPath("./contacts.mdb");
    Line 17:     DataTier data = new DataTier(db, "Contacts");
    Line 18: 
    Line 19:     protected void Page_Load(object sender, EventArgs e)

    Why am I getting this error? I can’t figure out what’s going on.

Answers

    • Marked as answer by

      Thursday, October 7, 2021 12:00 AM

I’m trying to make a simple button perform an action when pressed. Initially I was using vscode, but as I couldn’t solve the problem, I switched to visual studio 2017. For some reason the error persists.

The button has been removed from this link:

https://www.c-sharpcorner.com/article/unity-change-scene-on-button-click-using-c-sharp-scripts-in-unity/

Button code (internet sketch):

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

public class SceneChanger: MonoBehaviour {  
    public void Scene1() {  
        SceneManager.LoadScene("Scene1");  
    }  
    public void Scene2() {  
        SceneManager.LoadScene("Scene2");  
    }  
    public void Scene3() {  
        SceneManager.LoadScene("Scene3");  
    }  
}

Button code (my code):

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Windows.Forms;

public class botaoJogar : MonoBehaviour
{
    public Button btn_Jogar;

    void Start()
    {
        Button btn = btn_Jogar.GetComponent<Button>();
        btn.onClick.AddListener(TaskOnClick);
    }

    void TaskOnClick()
    {
        Debug.Log("You have clicked the button!");
    }
}

Image of the construction in unity:

enter image description here

Before, I was able to solve the CS0236 error using the answers from this link:

https://stackoverflow.com/questions/2883505/the-type-or-namespace-name-button-could-not-be-found-are-you-missing-a-using

The answer says to add the line using System.Windows.Forms; to the button code, but for some reason, now in visual studio, this error doesn’t go away.

Errors:

Assetsbotajogar.cs(4,22): error CS0234: The type or namespace name
‘Forms’ does not exist in the namespace ‘System.Windows’ (are you
missing an assembly reference?)

Assetsbotajogar.cs(8,12): error CS0246: The type or namespace name
‘Button’ could not be found (are you missing a using directive or an
assembly reference?)

Some community links, which I accessed:

https://stackoverflow.com/questions/42000798/how-do-i-add-assembly-references-in-visual-studio-code

https://stackoverflow.com/questions/49805204/adding-reference-to-another-project-from-visual-studio-code

https://stackoverflow.com/questions/2883505/the-type-or-namespace-name-button-could-not-be-found-are-you-missing-a-using

https://stackoverflow.com/questions/47412796/system-windows-forms-assembly-reference-in-vs-code

https://stackoverflow.com/questions/46582847/creating-a-windows-forms-application-in-c-sharp-using-dotnet-new

https://stackoverflow.com/questions/40562192/windows-form-application-on-visual-studio-code

https://stackoverflow.com/questions/48496542/forms-does-not-exist-in-the-namespace-system-windows

Other links:

https://docs.microsoft.com/en-us/visualstudio/ide/how-to-add-or-remove-references-by-using-the-reference-manager?view=vs-2019

https://docs.microsoft.com/pt-br/dotnet/csharp/language-reference/compiler-messages/cs0246

I don’t know what to do anymore, I feel like I tried to do everything I could, but windows forms simply don’t work. Visual studio 2017 has no bugs, just unity.

Installation I did in visual studio 2017:

enter image description here

enter image description here

Понравилась статья? Поделить с друзьями:
  • Ошибка компилятора cs0200
  • Ошибка компилятора cs0120
  • Ошибка компилятора cs0115
  • Ошибка компилятора cs0103
  • Ошибка компилятора cs0030