Search code examples
c#.net-8.0c#-12.0primary-constructor

C# Primary constructor with body?


Can I use a primary constructor and also define a constructor body?

Here is my attempt using a helper secondary constructor - I realize this is ambiguous, but I don't know if there is way to fix it... or do I have to resort to fields?

public class Thing(int a, int b) {
    public Thing(int a, int b) : this(a ,b) {
        // do some stuff using `a` and `b`
    }
}

Solution

  • If you need to have some logic in constructor just use the regular one, I would argue that there is no point in using primary constructors here since they were not designed for such things. If for some reason you still want to you can consider some, I would argue ugly, hacks.

    For example adding a dummy parameter to the primary constructor:

    public class Thing(int a, int b, object? _) 
    {
        public Thing(int a, int b) : this(a ,b, null) {
            // do some stuff using `a` and `b`,
            Console.WriteLine($"{a}_{b}");
        }
    }
    

    Or introducing some dummy field to makes some static callable method to do the job and assign the value:

    public class Thing(int a, int b)
    {
        private int _ = DoThing(a, b);
    
        private static int DoThing(int a, int b)
        {
            Console.WriteLine($"{a}_{b}");
            return a + b;
        }
    }
    

    As I said the workarounds are not pretty and in my opinion it's better to stick with "ordinary" constructors.

    Also note that at least some IDEs (don't have VS available at the moment) like Rider provide a refactoring which will expand the primary constructor into ordinary one:

    enter image description here

    enter image description here

    enter image description here

    So you can start designing class with primary constructor and then expand it into an ordinary one so it can save you some work you could consider tedious (also Rider/Resharper can generate the fields and assignment for you too with ordinary constructor).