0

some of my colleagues demand to avoid parameterless constructor and it's initialization completly. Because they tell me that a default initialization of a string property for example quickly hides the ability to find out the source of the error.

But a standard initialization of objects prevent the raise of a NullReferenceException in advance. And don't unit tests prevent those 'hard to find' errors?

So what is the best practice of doing this in C#?

What if i had a class with 10 Properties? Should the properties also be initialized via parameters of the constructor if i want to avoid the parameterless constructor? Isn't it to verbose?

For example i have this class, so people told me that i shouldn't do the default initialzation this way:

public class UserForCreationDto
{
    public UserForCreationDto()
    {
        Username = "";
        Email = "";
    }

    [Required]
    [MaxLength(100)]
    public string Username { get; set; }

    [Required]
    [MaxLength(100)]
    public string Email { get; set; }
}
Benjamin Martin
  • 576
  • 1
  • 8
  • 27
  • you can do default init in the property declaration `public string Username { get; set; } = string.Empty;` – Vidmantas Blazevicius Feb 18 '20 at 13:01
  • I read that the usage of "" or string.empty is the same from .Net 2.0 onwards. And what if i had a class which is composed inside of this one? – Benjamin Martin Feb 18 '20 at 13:02
  • 2
    @BenjaminMartin Why exactly do you want to initialize your properties to `""`? It sounds like you've got a case where code might accidentally access the properties before they're properly initialized. If that happens, surely it's better to know about it (via an NRE), rather than the application continuing to function, possibly incorrectly? – canton7 Feb 18 '20 at 13:03
  • @canton7 yeah i want to prevent the null reference exception by accident. – Benjamin Martin Feb 18 '20 at 13:05
  • 2
    @BenjaminMartin Right, so it sounds like you should follow your colleagues' advice, and leave them initialized to `null`? – canton7 Feb 18 '20 at 13:06

2 Answers2

2

If you want to intialize the properties to something else than their default values, you could do this directly in the definition:

public class UserForCreationDto
{
    [Required]
    [MaxLength(100)]
    public string Username { get; set; } = "";

    [Required]
    [MaxLength(100)]
    public string Email { get; set; } = "";
}

But if you want to prevent NullReferenceExceptions, you should also make the setters private. Given your current implementation, both properties can still be set to null explicitly.

That's why you should always - as a precaution - verify that a reference type variable is initialized before you try to access any of its properties:

if (!string.IsNullOrEmpty(dto.Username) { ... }
mm8
  • 163,881
  • 10
  • 57
  • 88
  • 2
    Given the name ("DTO") and the shown attributes, this class is used by a framework that will, through reflection, assign incoming data (for example through HTTP calls) to those properties, so making the setters private isn't going to solve anything. – CodeCaster Feb 18 '20 at 13:09
  • @CodeCaster: It's going to solve - the presumably inevitably - risk of getting a `NullReferenceException` when accessing the property. If a reference type property has a public setter, you can never guarantee that it's not `null`. – mm8 Feb 18 '20 at 13:11
  • If you make the properties private, you should of course also add a constructor that initializes them. Otherwise the type would be pretty meaningless. – mm8 Feb 18 '20 at 13:14
  • @mm8 But this means that the user of this class is forced to use the initialization via constructor User(string username, string email). But isnt it to verbose for classes with 10 properties for example? – Benjamin Martin Feb 18 '20 at 13:16
  • @BenjaminMartin: Yes. Whether it's verbose, or too verbose, is subjective I guess. But that's the only way to safely prevent a `NullReferenceException`. – mm8 Feb 18 '20 at 13:18
0

Initialization in a parameterless constructor should be avoided?

another way to ask this is

Side effects should be avoided?

there are benefits to avoiding side effects, which is probably what your colleagues are talking about without saying so many words. this is much interconnected with the benefits of immutability and dependency injection.

Kirk Horton
  • 368
  • 1
  • 7
  • Yeah but it also increases komplexity and memory footprint because you will have to handle changes with creation of new objects when the property setter is private. I dont see the Big benefit of using this approach since there is a warning system in c#8 (nullable ref types). Afterall this looks like a functional programming approach of letting the state everytime consistant. – Benjamin Martin Feb 19 '20 at 07:58