Blankdud
Blankdud

Reputation: 698

is it possible to set derived class default values without a constructor?

My goal is to make a static object that won't change, using a base class's member variables and abstract methods, as there will be multiple of these type of objects.

This is an example of what I want to do:

public abstract class BaseThing
{
    public string Name { get; set; }
    public string Description { get; set; }
    public decimal Cost { get; set;}

    public abstract void MethodThatDoesThings();
}

Then I want to have a derived object that has default values of those base variables, something like this (obviously doesn't work) :

public class DerivedThing : BaseThing
{
    Name = "Name1";
    Description = "Description1";
    Cost = 1.00;

    public override void MethodThatDoesThings()
    {
        //Actually does things
    }
}

Is something like this possible without using a constructor? Not that I'm against using them, I'm just genuinely curious. Right now I feel as though my only option is to create many static classes that have the same properties.

Upvotes: 1

Views: 2447

Answers (1)

Emre Kabaoglu
Emre Kabaoglu

Reputation: 13146

No, you should implement a constructor for derived class to set default values. If you want to set default values, you can do it like this;

public class DerivedThing : BaseThing
{
    public DerivedThing(string name = "Name", string description = "Description1", decimal cost = 1.0)
    {
        Name = name;
        Description = description;
        Cost = cost;
    }
    public override void MethodThatDoesThings()
    {

    }
}

Upvotes: 3

Related Questions