C#C
C#14mo ago
Jiry_XD

How to prevent nulls using this approach for Object Initializers?

In C# I have this class:
using System.Diagnostics.CodeAnalysis;
using System.Net.Mail;

namespace Domain.Customers;

public class EmailAddress
{
    private MailAddress email;

    public EmailAddress()
    {
        // Default constructor so I can use object initializer.
    }

    [SetsRequiredMembers]
    public EmailAddress(string email)
    {
        Email = email;
    }
    public required string Email
    {
        get => email.ToString();
        set => email = new MailAddress(value);
    }

}


As you can see I have two constructors, when using object initializers I need to use one of them. I like using object initializers using no constructor aka the default constructor but because I added it there is no default so I added it.

But now the problem is that people can call
new EmailAddress()
without passing an email and it can stay null that way?
How can I still be able to have an empty constructor so I can use object initializers without having the risk somoene calls
new EmailAdress();
?
Was this page helpful?