3

.NET 7 and C# 11 introduce a new modifier required. Documentation says:

The required modifier indicates that the field or property it's applied to must be initialized by all constructors or by using an object initializer. Any expression that initializes a new instance of the type must initialize all required members.

But what do I have to use when I want to implement a similar behavior in case I'm using C#10 or earlier? I.e., is there an alternative?

bahrep
  • 29,961
  • 12
  • 103
  • 150
  • 5
    I'm pretty sure there's no way to recreate the exact feature. The best you can do is create a constructor on the class that forces you to set the values. – juharr Dec 08 '22 at 16:53
  • 4
    If it would be that easy to recreate this behaviour I would say we would not required the new keyword in the language. – Guru Stron Dec 08 '22 at 16:55
  • 1
    If you really-really want to - you can create your own `RequiredAttribute` and write custom code analyzer for it but I would argue upgrading to .NET 7 would be time better spent. – Guru Stron Dec 08 '22 at 17:14

1 Answers1

1

Looking at the example in the reference you linked:

Microsoft Learn: required modifier (C# Reference)

I'm going to focus on the Person class:

public class Person
{
    public Person() { }

    [SetsRequiredMembers]
    public Person(string firstName, string lastName) =>
        (FirstName, LastName) = (firstName, lastName);

    public required string FirstName { get; init; }
    public required string LastName { get; init; }

    public int? Age { get; set; }
}

If I had properties that were required, I would only expose the constructor with the parameters you need:

public class Person
{
    //public Person() { }

    public Person(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public int? Age { get; set; }
}

Alternatively, you could make the constructor private and use a factory approach:

public class Person
{
    private Person() { }

    public static Person CreatePerson(string firstName, string lastName)
    {
        var person = new Person()
        {
            FirstName = firstName,
            LastName = lastName
        };
        return person;
    }

    public string FirstName { get; set; }
    public string LastName { get; set; }

    public int? Age { get; set; }
}