0

I want to be able to write code like this, and then there should be a compiler error if you fail to initialize the property when constructing the object:

    public record Person
    {
        public string Name { get; init; } // this produces a warning, but I don't think it should

        public static void Make()
        {
            new Person { // this should be a compiler error because I didn't initialize Name, but it's not
            };
        }
    }

Obviously the language isn't going to conform to my wishes, it isn't designed the way I wish it were. So I'm wondering if there is an alternative way of writing this to do what I want, without having to implement a constructor. Of course I could define a constructor that has a parameter for each property that needs to be set, but it feels like a lot of extra boilerplate code that features like record and init are designed to prevent from being necessary, but actually fail in this endeavor. An acceptable answer doesn't necessarily need to use the record feature, it's just an example of a feature that makes it seem like the designers of C# are trying to help us avoid this kind of extra boilerplate code. I'm looking for something similar to Kotlin's data classes, which record classes are, but they seem to break down for something as simple as requiring the property to bet set to something not null without having to basically write the same code three times for no reason (at the property definition, in the constructor parameters, and in the constructor implementation).

I've been out of the loop with C# for some time, so I guess I'm just wondering if I'm missing something or if defining a custom constructor really is the best you can do.

still_dreaming_1
  • 8,661
  • 6
  • 39
  • 56
  • I think records have an implicitly declared constructor – Daniel A. White Jul 10 '22 at 02:28
  • 1
    I don't think there is a way besides forcing it via a constructor parameter. You can at least look forward to the next version of the language, which has [added support](https://github.com/dotnet/csharplang/issues/3630#issuecomment-1166584239) for required properties. – bgfvdu3w Jul 10 '22 at 02:35
  • @bgfvdu3w nice find with the duplicate. It's kind of funny that the question was asked 10 years ago and soon there will be a nicer solution. At least it's progress. – still_dreaming_1 Jul 10 '22 at 03:11
  • In case this is interesting, PHP has this with constructor property promotion which can be combined with readonly properties. https://www.php.net/manual/en/language.oop5.decon.php#language.oop5.decon.constructor.promotion https://www.php.net/manual/en/language.oop5.properties.php#language.oop5.properties.readonly-properties – still_dreaming_1 Jul 10 '22 at 03:13
  • Wait! it does exist!!! `public record Person(string Name);` I'm adding this as an answer to the duplicate. – still_dreaming_1 Jul 10 '22 at 03:32

0 Answers0