Search code examples
c#default-constructor

Default and custom constructor


I have a simple question.

Assume that I have class like below.

    public class DamageToDeal
    {
        public bool enabled;
        public float value;
        public TDValue type;

        public DamageToDeal() { }

        public DamageToDeal(bool _enabled, float _value, TDValue _type)
        {
            enabled = _enabled;
            value = _value;
            type = _type;
        }

    }

I read that if I have custom constructor the default is not automaticaly generetared

Do I have to initialize fields myself with default values(0, null) or default constructor with empty body will do it anyway?

Or if the default constructor is initializing fields even if he has empty body ?


Solution

  • Memory allocated to a new class instance is cleared by the memory allocator. You only have to ensure that any fields you want to have a non-default value is assigned.

    This is documented here: Fundamentals of Garbage Collection:

    Managed objects automatically get clean content to start with, so their constructors do not have to initialize every data field.

    You do not need an empty parameterless constructor for this to happen. You would only add that constructor if you actually want to call it and that makes sense for the type.

    Also note that any field declarations that also states an initialization expression is lifted into constructors.

    If you do this:

    public TDValue type = new TDValue();
    

    then regardless of which constructor is called that field will have an instance reference to a new TDValue object.


    Note that the above is valid for classes, not for structs. For structs you need to ensure you assign all fields because memory is not always "allocated", it might be just reserved on the stack.