Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
CODE PROJECT For Those Who Code
  • Home
  • Articles
  • FAQ
Community
  1. Home
  2. General Programming
  3. C#
  4. A field initializer cannot reference the non-static field, method or property... help with code snippet

A field initializer cannot reference the non-static field, method or property... help with code snippet

Scheduled Pinned Locked Moved C#
helpdatabasedata-structures
7 Posts 3 Posters 1 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S Offline
    S Offline
    ssclaire
    wrote on last edited by
    #1

    I came across this error in my code that I cannot fix: A field initializer cannot reference the non-static field, method, or property 'ConsoleApplication.Polygon.colorValues' So extracted what I thought was the relevant part of the code to post and ask for help. The problem is that now this simplified code works:confused:. But I cannot find the problem in the original, full-length code. Since the original code is too long to post here, I was hoping I could post the "working" code here with the error. Maybe someone could tell me at least what to look for. This is my working code. The code creates a class with two fields. Both fields are enumerations...

    using System;

    namespace ConsoleApplication
    {
    class Program
    {
    enum ColorType {Red, Green, Blue, Yellow}; // all possible colors
    enum ShapeType {Square, Circle, Triangle}; // all possible shapes

        class Polygon
        {
            // each polygon has a color and a shape
            public ColorType Color { get; set; }
            public ShapeType Shape { get; set; }
    
            private Polygon() { }       // hide the default constructor
            public Polygon(ColorType color, ShapeType shape)
            {
                Color = color;
                Shape = shape;
            }
        }
    

    The code then tries to create an array of these classes. The elements of the array contain each possible combination of the enumerations. To do that, I use Enum.GetValues() to get an array of possible enum values and use the Array.Length property to figure out the size of the array I will need to hold all the combinations.

        static void Main(string\[\] args)
        {
            Array colorValues = Enum.GetValues(typeof(ColorType));
            Array shapeValues = Enum.GetValues(typeof(ShapeType));
            Polygon\[\] allPolygons = new Polygon\[`colorValues`.Length \* `shapeValues`.Length\];
    
            int index = 0;
            foreach (ColorType color in colorValues)
            {
                foreach (ShapeType shape in shapeValues)
                {
                    allPolygons\[index\] = new Polygon(color, shape);
                    Console.WriteLine(allPolygons\[index\]);
                    index++;
                }
            }
        }
    }
    

    }

    I underlined the portion (above) that is generating the error: A field initializer cannot reference the non-static field, method, or pr

    S C S 3 Replies Last reply
    0
    • S ssclaire

      I came across this error in my code that I cannot fix: A field initializer cannot reference the non-static field, method, or property 'ConsoleApplication.Polygon.colorValues' So extracted what I thought was the relevant part of the code to post and ask for help. The problem is that now this simplified code works:confused:. But I cannot find the problem in the original, full-length code. Since the original code is too long to post here, I was hoping I could post the "working" code here with the error. Maybe someone could tell me at least what to look for. This is my working code. The code creates a class with two fields. Both fields are enumerations...

      using System;

      namespace ConsoleApplication
      {
      class Program
      {
      enum ColorType {Red, Green, Blue, Yellow}; // all possible colors
      enum ShapeType {Square, Circle, Triangle}; // all possible shapes

          class Polygon
          {
              // each polygon has a color and a shape
              public ColorType Color { get; set; }
              public ShapeType Shape { get; set; }
      
              private Polygon() { }       // hide the default constructor
              public Polygon(ColorType color, ShapeType shape)
              {
                  Color = color;
                  Shape = shape;
              }
          }
      

      The code then tries to create an array of these classes. The elements of the array contain each possible combination of the enumerations. To do that, I use Enum.GetValues() to get an array of possible enum values and use the Array.Length property to figure out the size of the array I will need to hold all the combinations.

          static void Main(string\[\] args)
          {
              Array colorValues = Enum.GetValues(typeof(ColorType));
              Array shapeValues = Enum.GetValues(typeof(ShapeType));
              Polygon\[\] allPolygons = new Polygon\[`colorValues`.Length \* `shapeValues`.Length\];
      
              int index = 0;
              foreach (ColorType color in colorValues)
              {
                  foreach (ShapeType shape in shapeValues)
                  {
                      allPolygons\[index\] = new Polygon(color, shape);
                      Console.WriteLine(allPolygons\[index\]);
                      index++;
                  }
              }
          }
      }
      

      }

      I underlined the portion (above) that is generating the error: A field initializer cannot reference the non-static field, method, or pr

      S Offline
      S Offline
      S Senthil Kumar
      wrote on last edited by
      #2

      Your code works probably because you moved initialization of colorValues inside Main. Your original code probaly initialized them as part of the field declaration, like

      class Program
      {
      Array colorValues = Enum.GetValues(typeof(ColorType));
      Polygon[] allPolygons = new Polygon[colorValues.Length * shapeValues.Length];
      }

      That doesn't work - instance field initializers cannot refer to other instance field initializers. That means that you cannot refer to colorValues from any other instance field initializer. The typical solution is to move the initialization code to the constructor of the class.

      Regards Senthil [MVP - Visual C#] _____________________________ My Blog | My Articles | My Flickr | WinMacro

      S 1 Reply Last reply
      0
      • S ssclaire

        I came across this error in my code that I cannot fix: A field initializer cannot reference the non-static field, method, or property 'ConsoleApplication.Polygon.colorValues' So extracted what I thought was the relevant part of the code to post and ask for help. The problem is that now this simplified code works:confused:. But I cannot find the problem in the original, full-length code. Since the original code is too long to post here, I was hoping I could post the "working" code here with the error. Maybe someone could tell me at least what to look for. This is my working code. The code creates a class with two fields. Both fields are enumerations...

        using System;

        namespace ConsoleApplication
        {
        class Program
        {
        enum ColorType {Red, Green, Blue, Yellow}; // all possible colors
        enum ShapeType {Square, Circle, Triangle}; // all possible shapes

            class Polygon
            {
                // each polygon has a color and a shape
                public ColorType Color { get; set; }
                public ShapeType Shape { get; set; }
        
                private Polygon() { }       // hide the default constructor
                public Polygon(ColorType color, ShapeType shape)
                {
                    Color = color;
                    Shape = shape;
                }
            }
        

        The code then tries to create an array of these classes. The elements of the array contain each possible combination of the enumerations. To do that, I use Enum.GetValues() to get an array of possible enum values and use the Array.Length property to figure out the size of the array I will need to hold all the combinations.

            static void Main(string\[\] args)
            {
                Array colorValues = Enum.GetValues(typeof(ColorType));
                Array shapeValues = Enum.GetValues(typeof(ShapeType));
                Polygon\[\] allPolygons = new Polygon\[`colorValues`.Length \* `shapeValues`.Length\];
        
                int index = 0;
                foreach (ColorType color in colorValues)
                {
                    foreach (ShapeType shape in shapeValues)
                    {
                        allPolygons\[index\] = new Polygon(color, shape);
                        Console.WriteLine(allPolygons\[index\]);
                        index++;
                    }
                }
            }
        }
        

        }

        I underlined the portion (above) that is generating the error: A field initializer cannot reference the non-static field, method, or pr

        S Offline
        S Offline
        ssclaire
        wrote on last edited by
        #3

        Okay, I think it is the "cannot reference the non-static" part of the error which is relevant. If I move the Main() code into a class:

            class MyClass
            {
                Array colorValues = Enum.GetValues(typeof(ColorType));
                Array shapeValues = Enum.GetValues(typeof(ShapeType));
                Polygon\[\] allPolygons = new Polygon\[colorValues.Length \* shapeValues.Length\];
        
                public MyClass()
                {
                    int index = 0;
                    foreach (ColorType color in colorValues)
                    {
                        foreach (ShapeType shape in shapeValues)
                        {
                            allPolygons\[index\] = new Polygon(color, shape);
                            Console.WriteLine(allPolygons\[index\]);
                            index++;
                        }
                    }
                }
            }
        

        ...and call it from Main()

            static void Main(string\[\] args)
            {
                MyClass myClass = new MyClass();
            }
        

        I get the error. But how do I work around that? How would I create the private allPolygons array? What am I actually doing wrong?

        C S 2 Replies Last reply
        0
        • S ssclaire

          I came across this error in my code that I cannot fix: A field initializer cannot reference the non-static field, method, or property 'ConsoleApplication.Polygon.colorValues' So extracted what I thought was the relevant part of the code to post and ask for help. The problem is that now this simplified code works:confused:. But I cannot find the problem in the original, full-length code. Since the original code is too long to post here, I was hoping I could post the "working" code here with the error. Maybe someone could tell me at least what to look for. This is my working code. The code creates a class with two fields. Both fields are enumerations...

          using System;

          namespace ConsoleApplication
          {
          class Program
          {
          enum ColorType {Red, Green, Blue, Yellow}; // all possible colors
          enum ShapeType {Square, Circle, Triangle}; // all possible shapes

              class Polygon
              {
                  // each polygon has a color and a shape
                  public ColorType Color { get; set; }
                  public ShapeType Shape { get; set; }
          
                  private Polygon() { }       // hide the default constructor
                  public Polygon(ColorType color, ShapeType shape)
                  {
                      Color = color;
                      Shape = shape;
                  }
              }
          

          The code then tries to create an array of these classes. The elements of the array contain each possible combination of the enumerations. To do that, I use Enum.GetValues() to get an array of possible enum values and use the Array.Length property to figure out the size of the array I will need to hold all the combinations.

              static void Main(string\[\] args)
              {
                  Array colorValues = Enum.GetValues(typeof(ColorType));
                  Array shapeValues = Enum.GetValues(typeof(ShapeType));
                  Polygon\[\] allPolygons = new Polygon\[`colorValues`.Length \* `shapeValues`.Length\];
          
                  int index = 0;
                  foreach (ColorType color in colorValues)
                  {
                      foreach (ShapeType shape in shapeValues)
                      {
                          allPolygons\[index\] = new Polygon(color, shape);
                          Console.WriteLine(allPolygons\[index\]);
                          index++;
                      }
                  }
              }
          }
          

          }

          I underlined the portion (above) that is generating the error: A field initializer cannot reference the non-static field, method, or pr

          C Offline
          C Offline
          Christian Graus
          wrote on last edited by
          #4

          ssclaire wrote:

          static void Main(string[] args) { Array colorValues = Enum.GetValues(typeof(ColorType)); Array shapeValues = Enum.GetValues(typeof(ShapeType)); Polygon[] allPolygons = new Polygon[colorValues.Length * shapeValues.Length];

          If a method is static, it can't access a non static property as it has no instance to refer to.

          Christian Graus Please read this if you don't understand the answer I've given you "also I don't think "TranslateOneToTwoBillion OneHundredAndFortySevenMillion FourHundredAndEightyThreeThousand SixHundredAndFortySeven()" is a very good choice for a function name" - SpacixOne ( offering help to someone who really needed it ) ( spaces added for the benefit of people running at < 1280x1024 )

          1 Reply Last reply
          0
          • S ssclaire

            Okay, I think it is the "cannot reference the non-static" part of the error which is relevant. If I move the Main() code into a class:

                class MyClass
                {
                    Array colorValues = Enum.GetValues(typeof(ColorType));
                    Array shapeValues = Enum.GetValues(typeof(ShapeType));
                    Polygon\[\] allPolygons = new Polygon\[colorValues.Length \* shapeValues.Length\];
            
                    public MyClass()
                    {
                        int index = 0;
                        foreach (ColorType color in colorValues)
                        {
                            foreach (ShapeType shape in shapeValues)
                            {
                                allPolygons\[index\] = new Polygon(color, shape);
                                Console.WriteLine(allPolygons\[index\]);
                                index++;
                            }
                        }
                    }
                }
            

            ...and call it from Main()

                static void Main(string\[\] args)
                {
                    MyClass myClass = new MyClass();
                }
            

            I get the error. But how do I work around that? How would I create the private allPolygons array? What am I actually doing wrong?

            C Offline
            C Offline
            Christian Graus
            wrote on last edited by
            #5

            ssclaire wrote:

            Array colorValues = Enum.GetValues(typeof(ColorType)); Array shapeValues = Enum.GetValues(typeof(ShapeType)); Polygon[] allPolygons = new Polygon[colorValues.Length * shapeValues.Length];

            Seems to me like these should be static anyhow, they don't change between instances, right ?

            Christian Graus Please read this if you don't understand the answer I've given you "also I don't think "TranslateOneToTwoBillion OneHundredAndFortySevenMillion FourHundredAndEightyThreeThousand SixHundredAndFortySeven()" is a very good choice for a function name" - SpacixOne ( offering help to someone who really needed it ) ( spaces added for the benefit of people running at < 1280x1024 )

            1 Reply Last reply
            0
            • S ssclaire

              Okay, I think it is the "cannot reference the non-static" part of the error which is relevant. If I move the Main() code into a class:

                  class MyClass
                  {
                      Array colorValues = Enum.GetValues(typeof(ColorType));
                      Array shapeValues = Enum.GetValues(typeof(ShapeType));
                      Polygon\[\] allPolygons = new Polygon\[colorValues.Length \* shapeValues.Length\];
              
                      public MyClass()
                      {
                          int index = 0;
                          foreach (ColorType color in colorValues)
                          {
                              foreach (ShapeType shape in shapeValues)
                              {
                                  allPolygons\[index\] = new Polygon(color, shape);
                                  Console.WriteLine(allPolygons\[index\]);
                                  index++;
                              }
                          }
                      }
                  }
              

              ...and call it from Main()

                  static void Main(string\[\] args)
                  {
                      MyClass myClass = new MyClass();
                  }
              

              I get the error. But how do I work around that? How would I create the private allPolygons array? What am I actually doing wrong?

              S Offline
              S Offline
              S Senthil Kumar
              wrote on last edited by
              #6

              Just move the code to the constructor and you'll be fine

              class MyClass
              {
              Array colorValues = Enum.GetValues(typeof(ColorType));
              Array shapeValues = Enum.GetValues(typeof(ShapeType));
              Polygon[] allPolygons;

                      public MyClass()
                      {
                         allPolygons =  = new Polygon\[colorValues.Length \* shapeValues.Length\];
                      ...
                      }
              

              }

              Regards Senthil [MVP - Visual C#] _____________________________ My Blog | My Articles | My Flickr | WinMacro

              1 Reply Last reply
              0
              • S S Senthil Kumar

                Your code works probably because you moved initialization of colorValues inside Main. Your original code probaly initialized them as part of the field declaration, like

                class Program
                {
                Array colorValues = Enum.GetValues(typeof(ColorType));
                Polygon[] allPolygons = new Polygon[colorValues.Length * shapeValues.Length];
                }

                That doesn't work - instance field initializers cannot refer to other instance field initializers. That means that you cannot refer to colorValues from any other instance field initializer. The typical solution is to move the initialization code to the constructor of the class.

                Regards Senthil [MVP - Visual C#] _____________________________ My Blog | My Articles | My Flickr | WinMacro

                S Offline
                S Offline
                ssclaire
                wrote on last edited by
                #7

                S. Senthil Kumar wrote:

                The typical solution is to move the initialization code to the constructor of the class.

                Cool. Moving the initialization of colorValues, shapeValues, and allPolygons to the constructor worked. Thanks. I think the full code design is "cleaner" when I declare the colorValues/shapeValues arrays as static (as mentioned below). Thank you everyone.

                1 Reply Last reply
                0
                Reply
                • Reply as topic
                Log in to reply
                • Oldest to Newest
                • Newest to Oldest
                • Most Votes


                • Login

                • Don't have an account? Register

                • Login or register to search.
                • First post
                  Last post
                0
                • Categories
                • Recent
                • Tags
                • Popular
                • World
                • Users
                • Groups