none
Objects in array, get properties problem RRS feed

  • Question

  • Hi,

    I´m working on a projekt I have to do in school (beginner at c#) and I am totally stuck.

    I have to add objects to my Array and so far so good.

    Then i need to print out in the console the objects and the properties for them and this is where I have problems. I have gotten a file that I should work from with two classes.

    One with the main that just starts a method in Another class. 

    That class is not static and when I try to use get

    Then I have a class with my objects.

    When I try to loop through my Array to get the properties from my Array I get a message.

    ""An object reference is required for the non static field, method or property.""

    I know this has something to do with static and not static but I just can´t find information on what the problem is.

    Is it possible to get properties from objects from a non static class or have I missunderstood Everything and I should put it in the main.

    Monday, November 20, 2017 10:46 PM

Answers

  • If you are creating an object, and you know what it is, then you should use that exact type rather than just 'object':

    private Soda[] bottles= new Soda[24]; 

    Then you would be able to access the price property directly because the system knows what the type is:

    Soda soda = bottles[i]; // no need to type cast
    if (soda != null) { 
        Console.WriteLine(soda.price);
    }
    



    • Edited by RJP1973 Tuesday, November 21, 2017 1:25 PM
    • Proposed as answer by Fei HuModerator Wednesday, November 22, 2017 8:35 AM
    • Marked as answer by Medusa3604 Wednesday, November 22, 2017 9:53 AM
    Tuesday, November 21, 2017 1:24 PM

All replies

  • Greetings Medusa.

    Statics are a real problem for a lot of beginners. It would take all day to explain all the finer points, but the essence is that something that is static exists only once, whereas something that is non-static can exist any number of times.

    For example, you might create a class called Car which is non-static and use it to store information about a number of Cars called car1, car2, car3, and so on.

    An example of a static class is Math, which holds mathematical functions and constants. We never create a math1, math2, and so on, we just use Math (like Math.Cos, Math.Sin, Math.Pi...).

    What that error message is telling you is that you have a class that is non-static but you are trying to use it as if it is static. Like Car.SteeringWheel instead of car1.SteeringWheel (each individual car has its own steering wheel, there is no steering wheel for the class as a whole).

    If you post your code we can probably give you more exact advice what to do in your case.
    Tuesday, November 21, 2017 12:30 AM
  • Hello Medusa4604,

    >>An object reference is required for the non static field, method or property

    The error message usually occurs when you are calling a non static property from a static method. In this case, You want to loop the array in Main static method. I suspect the array is non-static property. As for a workaround, you will need to either make the property static or create an instance of program. I create a simple demo to reappear the error.

    class People
        {
            public string name;
        }
    
        class Program
        {
            People[] ps = new People[] { new People { name = "xxxx" }, new People { name = "yyyy" } };
    
            static void Main(string[] args)
            {
                foreach (var s in ps)
                {
    
                }
            }
        }

    Workaround as below

    1. use  static modify the property

     static  People[] ps = new People[] { new People { name = "xxxx" }, new People { name = "yyyy" } };


    2.Or create a instance of program.

    People[] ps = new People[] { new People { name = "xxxx" }, new People { name = "yyyy" } };
    
            static void Main(string[] args)
            {
                Program p = new Program();
                foreach (var s in p.ps)
                {
    
                }
            }

    Sincerely,

    Fei Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, November 21, 2017 5:46 AM
    Moderator
  • Hi and thank you all, I feel like I really need to get a hang of this to understand the whole Picture and you replies are very helpfull.

    I post some code here and see if you understand what I am doing wrong. The Project is in Swedish, I have tried to translate the Words, hope I didn´t miss anything.

    This is just pieces of the code since it´s preety much.

    class Program
        {
            static void Main(string[] args)
            {
                var sodacrate = new Sodacrate();
                sodacrate.Run();

    //Method Run just shows a menu.

    class Sodacrate
        {
            private object[] bottles= new object[24];              //Array.

    Console.WriteLine("Price of bottle?");                        // User enters the price.
                int price= int.Parse(Console.ReadLine());

                bool occupied= false;
                do
                {
                    int i = 0;

                    if (bottles[i] == null)                                      // If flaskor = empty, add new object of 
                    {                                                                      Soda.
                        bottles[i] = new Soda(price);                        
                        occupied= true;
                    }
                    i++;
                }
                while (occupied= false);

    class Soda // Class of soda bottles. The class of the objects.
        {
            private int price{ get; set; }

            public Soda(int _price)
            {
                price= _price;
            }

    // Now I want to print out the price of the bottles in the Array. I need to get the price from each bottle and here I just dont understand what to do. 

    class Sodacrate

            public  void print_crate()
            {
                for (int i = 0; i < bottles.Length; i++)
                {
                    ?
                }
            }

    I really appreciate your efforts.

    Tuesday, November 21, 2017 7:44 AM
  • Hello Medusa3604,

    >>I need to get the price from each bottle and here I just don‘t understand what to do.

    You should do the below steps.

    1.Use "public" keywords to modify the "price" property in Soda class.

      public int price { get; set; }

    https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/access-modifiers

    2.use the below code to print the price.

    for (int i = 0; i < bottles.Length; i++)
                 {
                     Soda soda = (Soda)bottles[i];
                     if (soda != null) { 
                     Console.WriteLine(soda.price);
                    }
                 }

    Sincerely,

    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, November 21, 2017 9:40 AM
    Moderator
  • If you are creating an object, and you know what it is, then you should use that exact type rather than just 'object':

    private Soda[] bottles= new Soda[24]; 

    Then you would be able to access the price property directly because the system knows what the type is:

    Soda soda = bottles[i]; // no need to type cast
    if (soda != null) { 
        Console.WriteLine(soda.price);
    }
    



    • Edited by RJP1973 Tuesday, November 21, 2017 1:25 PM
    • Proposed as answer by Fei HuModerator Wednesday, November 22, 2017 8:35 AM
    • Marked as answer by Medusa3604 Wednesday, November 22, 2017 9:53 AM
    Tuesday, November 21, 2017 1:24 PM
  • Man you just made my day, Everything works perfect now, got more done in 3 hours than in the last week :)

    Thank you so much for your help and thank you to all others that has replied

    Tuesday, November 21, 2017 11:45 PM
  •  Hello Medusa3604,

    If the issues have been solved ,you could close the thread by marking the useful reply as answer. This can  be beneficial to other community members reading this thread. Thanks a lot.

    Best regards,

    Fei Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, November 22, 2017 8:19 AM
    Moderator