0

I got an issue With OOP with C#.

It says that "Member "" can't be accessed with instance reference. Qualify it with a type name instead."

Error: Click Here

Code for the reference:



class Car
    {
        
        public static String Model;
        public static int Year;
        public static String Brand;

        public Car(string Name, string Model, int Year, String Brand)
        {
            
            this.Model = Model;
            this.Year = Year;
            this.Brand = Brand;
        }

        public static void Drive()
        {
            Console.WriteLine($"Your car - {Car.Brand} {Car.Model} made in {Car.Year} can be driven now.");
        }
    }


I checked this website:

member cannot be accessed with an instance reference; qualify it with a type name instead

But still not working.

  • Side note, `static` members/properties only can be assigned in `static` constructor. And for your scenario, I don't see any reason to use `static` for those fields. – Yong Shun May 15 '22 at 06:31

2 Answers2

2

Remove the word static everywhere. Apart from in the case of static void Main, which is required to get your program going (but actually might not be visible any more if you're using very modern C#) do not use the word static at all when you're learning OOP; it shoots you in the foot because it essentially "turns off" the object orientation part of "object orientated programming"

It has its uses that you will appreciate as your experience grows, but right now all it will do is confuse you and make things harder to explain; we are trying to get you to think in terms of making a blueprint for a Car (that's the class), and then churning multiple different instances of cars (using the word new to make one car as a Tesla and another as a Ford, and appreciate that two different cars' data are somewhere in your computer memory..) - using static means there is only ever one of something, which will really cripple your ability to get on board with the usefulness of having multiples..

TLDR; don't use it - if you find yourself sticking it in "to get something working" then it means there is a problem elsewhere - come ask us for help on how to get it working without static, whatever "it" may be..

Caius Jard
  • 72,509
  • 5
  • 49
  • 80
0

This should work:

public static void Drive()
        {
            Console.WriteLine($"Your car - {Brand} {Model} made in {Year} can be driven now.");
        }

Inside Car class you should not use class name for accessing properties even static ones.

teder.ted
  • 11
  • 4