0

I have a question regarding initializing a property in c#.

I have a property called FirstName. I am then asked to initialize the property. The are two different ways to do it, but I do not understand the different outcome of it. Is one way better than the other?

  Person perOne = new Person()

The first way to do it is to do it using the constructor like this:

public Person()
{
FirstName = "Edward";
}

The second way to do it would be to use the object like this:

perOne.FirstName = "Edward";

Is it correct to say that the difference would be that the second way creates the FirstName of the object, while the first way just create a general FirstName (even though it was created inside the constructor used to create the object)?

David
  • 159
  • 8
  • This [thread](https://stackoverflow.com/questions/19138195/c-sharp-assign-data-to-properties-via-constructor-vs-instantiating) may help you. – 大陸北方網友 Jan 13 '21 at 09:11
  • 1
    Which way makes sense to you? Is a person always `Edward` ? Or said another way, are babies constructed with a default name `Edward`? Doesn't really make sense... However you can have a constructor parameter to set the name... or as you have done, set it down the track... – TheGeneral Jan 13 '21 at 09:15
  • 1
    There are more ways to initilize `FirstName`. If you set value in constructor or using field/auto-property initializer, then all your `Person` by default `Edward` (which is wrong). Having empty `FirstName` is also not good (if someone forget to set property value like in your second way), perhaps the best is to use constructor with parameter. – Sinatr Jan 13 '21 at 09:23
  • 1
    If the person always have a first name I would argue it is best to use a constructor parameter and set the property in the constructor. That way you can guarantee that it will be set, and use appropriate validation to ensure the Person object is valid when it leaves the constructor. – JonasH Jan 13 '21 at 09:48

0 Answers0