Reputation: 35
My situation would be similar to as follows.
public abstract class Mammal{ public Mammal( name, legs ){ ... } }
public class Dog{ public Dog( name, legs ) : base ( name, legs ) { ... } }
I don't want to always do Dog dog = new Dog( "fido", 4 );
I'd rather just have "legs = 4" in the Dog constructor and pass in the name only.
However, whenever I try to leave "legs" out of the constructors, it tells me certain fields are inaccessible due to protection level.
I am using getters and setters, they are all public.
EDIT: Here is one of the original broken classes -
public Soil(int idNo, string soilName, string prefabName)
: base(idNo, soilName, price, weight, size, madeOf, prefabName, iconName){
Price = 0;
Capacity = 1;
CanHoldSizes = new ContainerSizes[] {ContainerSizes.seed};
Contents = new Item[Capacity];
}
Instead of having to put all 8 parameters in to new Soil(), I wanted to just put the 4 in that would be different for each new Soil() and have the constructor set the rest to defaults.
This creates errors such as: "`Item.price' is inaccessible due to its protection level"
Upvotes: 2
Views: 498
Reputation: 11941
You can do this
public class Dog
{
public Dog(string name) : base ( name, 4) { }
//OR this
public Dog(string name, int legs = 4) : base ( name, legs) { }
}
The first constructors will always create a Mammal with 4 legs.
The second one will allow you to do this new Dog("MyDog")
but the compiler will replace this code by new Dog("MyDog",4)
.
Of course, using the second one, you'll still be able to do this new Dog("MyDog",3)
, and it'll create a dog with 3 legs.
Upvotes: 6
Reputation: 52280
I must be missing something. Isn't it as simple as this?
public class Dog
{
public Dog(string name) : base (name, 4)
{
}
}
Upvotes: 3