Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

A field initializer cannot reference the non-static field, method, or property 'name'

I’m a c# begginer and my code generates the CS0236 error, I’ve created a class with a
LvlData struct that contains a couple of variables and a readLvl function that takes the directory of a text file and returns a LvlData based on that.

However, when trying to use it (public LvlData CurrentLevelData = readLvl("../Level/Def/lvl.txt");) it throws an A field initializer cannot reference the non-static field, method, or property ‘name’. error.

Here’s the LevelManager class:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 class LevelManager
    {
        public LevelManager()
        {
           
        }

        public struct LvlData
        {
            public LvlData(int width, int height, string tiledata,string colisiondata,string flag = "0")
            {
                Width = width;
                Height = height;
                TileData = tiledata;
                CollisionData = colisiondata;
                Flag = flag; //Deafult 0 Beacuse we sometimes don't have it
            }

            public int Width { get; }
            public int Height { get; }
            public string TileData { get; }
            public string CollisionData { get; }
            public string Flag { get; }
        }
        public LvlData readLvl(string dir)
        {
            int w, h;
            string tiled, colliiond, f;

            // Read the file 
            string[] lines = System.IO.File.ReadAllLines(dir);

            w = int.Parse(lines[0]);
            h = int.Parse(lines[1]);

            tiled = lines[2];
            colliiond = lines[3];
            f = lines[4];

            LvlData deta = new LvlData(w, h, tiled, colliiond, f);

            return deta;
        }

        public LvlData CurrentLevelData = readLvl("../Level/Def/lvl.txt");

        
}

>Solution :

you have to move a method call to the constructor

 class LevelManager
    {
      public LvlData CurrentLevelData {get; set;}

       public LevelManager()
        {
           CurrentLevelData = readLvl("../Level/Def/lvl.txt");
        }

or make the method and property static

public static LvlData CurrentLevelData {get; set; } = readLvl("../Level/Def/lvl.txt");

public static LvlData readLvl(string dir)
{
.....
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading