Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a reason why a constructor needs a body in C# if it has an initializer?

Tags:

c#

It annoys me that I am required to have them, for an example consider the case

public class IsEquipmentAvailable : Specification<Equipment>
{
    public IsEquipmentAvailable() : base(equipment => equipment.CartEquipments
        .All(o => o.RentState == RentState.Done))
}

However, I am not allowed to write this as I need to add {}, in c# that is at least 2 extra lines of the boilerplate code that do nothing. If I want to support directed expression graph chain calls or just instantiating element from an expression, it becomes even worse.

public class IsEquipmentAvailable : Specification<Equipment>
{
    public IsEquipmentAvailable(Expression<Func<Equipment, bool>> expression) 
        : base(expression)
    {
    }

    public IsEquipmentAvailable(ISpecification<Equipment> specification) 
        : base(specification)
    {
    }

    public IsEquipmentAvailable() : base(equipment => equipment.CartEquipments
        .All(o => o.RentState == RentState.Done))
    {
    }
}

The functional programming side of me laughs from ignorance because he does not know better. Sometimes there are valid reasons why things are the way they are, so I would like to know reasoning behind this.

like image 440
Margus Avatar asked Oct 31 '22 03:10

Margus


1 Answers

The language does allow for an omission - just the opposite one to the one you we're looking for (10.11.1):

All instance constructors (except those for class object) implicitly include an invocation of another instance constructor immediately before the constructor-body

and:

If an instance constructor has no constructor initializer, a constructor initializer of the form base() is implicitly provided. Thus, an instance constructor declaration of the form

C(...) {...}

is exactly equivalent to

C(...): base() {...}

So, there's no exception for constructors that have initializers because, per the language spec, all constructors do in fact have initializers.


Also, the language is quite consistent here, when you think about it - the only places where you're allowed to completely omit the body of a method are where you are, specifically, prohibited from supplying a body - such as extern constructors, as mentioned in the comments, or abstract methods. Everywhere else, you must supply a body, even if you choose to make it empty.

like image 95
Damien_The_Unbeliever Avatar answered Nov 08 '22 09:11

Damien_The_Unbeliever