Search code examples
c#classconventions

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?


Solution

  • 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.