Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# pre initialized class

What is the best practice to create pre-initialized class. For example

Chip chip = new Atmega8();

I would like to have its properties already defined like:

chip.Name = "Atmega8 AVR Chip";

and so on.

How to achieve it in C#?
Should I use readonly public properties or property with private set?

like image 254
aambrozkiewicz Avatar asked Jan 26 '26 05:01

aambrozkiewicz


1 Answers

Have your constructor initialize the values:

class Atmega8 {
    public Atmega8 ()
    {  
        Name = "Atmega8 AVR Chip";
    }

    public string Name { get; set; }
}

If you intend Name to be the same for all instances, it might make sense to declare it abstract in the base class and override the getter:

abstract class Chip {
    public abstract string Name { get; }
}

class Atmega8 : Chip {
    public override string Name {
        get { return "Atmega8 AVR Chip"; }
    }
}

Because we haven't defined a set method, the value cannot be changed, much like a readonly variable except it isn't even stored anywhere and just returned on each call.

like image 198
Dan Abramov Avatar answered Jan 28 '26 20:01

Dan Abramov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!