c# - Static integer in class not accessible in foreach loop? -


here code i'm using:

    class program     {         static standardroom room55 = new standardroom(55);         static standardroom room45 = new standardroom(45);         static list<standardroom> roommap = new list<standardroom>() { room45, room55 };      static void main(string[] args)     {         foreach(standardroom room in roommap)         {             console.writeline(room.roomid);            }     }  class standardroom {     public static int roomid;      public standardroom(int roomnum)     {         roomid = roomnum;     } } 

my problem is:

member "room.roomid" cannot accessed instance reference; qualify type name instead.

i'm not sure how fix this.

class standardroom {     public int roomid {get; set;} // modified } 

you not want static field here, want public instance property.

if want make sure cannot changed outside class make setter private or remove fine c# v6.

class standardroom {     public int roomid {get; private set;} // modified     public standardroom(int roomnum)     {         this.roomid = roomnum;     } } 

now why not static? static single instance tracked on type itself. want define roomid every room instance has instance variable. should hardly ever use static fields / properties.


Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -