Home > other >  Assign enum value c#
Assign enum value c#

Time:03-28

I have a class called Parrot that inherits from Bird class that inherits from Animal class. Class Animal has enum genderType. However, when I am trying to make a new object of Parrot and assign the enum value like this:

Animal.cs

internal class Animal
    {
        private int id;
        private String name;
        private int age;
        enum GenderType { Female, Male, Unknown }

        GenderType gender;
        public int Id { get => id; set => id = value; }
        public string Name { get => name; set => name = value; }
        public int Age { get => age; set => age = value; }

    }
}

Form1.cs

.
.
          pr = new parrot();
          pr.Name = name.Text;
          pr.Age = int.Parse(age.Text);
          ((parrot)pr).Color = extraInfo.Text;
          ((parrot)pr).FlyingSpeed = int.Parse(fSpeed.Text);
          pr.gender = GenderType.Female;
.
.

Bird.cs

 internal class Bird:Animal
    {
        private int flyingSpeed;

        public int FlyingSpeed { get => flyingSpeed; set => flyingSpeed = value; }
    }
}

parrot.cs

internal class parrot:Bird
    {
        private string color;

        public string Color { get => color; set => color = value; }
    }
}

I am getting these erors:

The name 'genderType' does not exist in the current context

'Animal.genderType' is a type but is used like a variable

'genderType': cannot reference a type through an expression; try 'Animal.genderType' instead

CodePudding user response:

Inner types in classes, like:

class A {
    enum B { C = 0 }
}

Are not variables. If you want a variable bound to Animal and change it when needed you need a variable:

class Animal {
    //type
    enum GenderType { ... }

    //variable
    GenderType gender;
}

//code:
var animal = new Animal();
animal.gender = GenderType.Female;
  • Related