3
class Student
{  
     private string firstName;

     public string FirstName
     {
        get
        {
            return firstName;
        }
        set
        {
            firstName = value; // Possible logical checks may be implemented here in the future
        }
     }

     public Student (firstName)
     {

         this.firstName = firstName; // Option 1
         // Or
         FirstName = firstName; // Option 2

     }
 }

which of the two lines is more standard?

do we use the private or the public members in the constructor?

yazanpro
  • 4,512
  • 6
  • 44
  • 66
  • 2
    You should separate your question from your code snippet – Sayse Jul 10 '13 at 18:28
  • I prefer to use the public property in my 'new object' constructors, but the private property in my 'clone object' constructors. It's situation-dependent and subject to opinion. – tuespetre Jul 10 '13 at 18:29
  • The purpose of having a public property like that, as opposed to just exposing the member itself, is if you wish to do something in the future with the data as it comes in, you'd define that logic in the Property's setter, instead of having to handle it everywhere before the property is set. – crush Jul 10 '13 at 18:30
  • 1
    In your example it does not really matter. But if you had logic in setter then it would matter. Maybe at construction you don't want to hit that logic. Also, if you were to create proxy, it would complain about accessing private member in constructor. In other words, no method is standard and depends on your situation. – epitka Jul 10 '13 at 18:32

6 Answers6

9

You could go with option 3

 public string FirstName {get; set;}
 public Student (firstName)
 {
     FirstName = firstName;
 }
Sayse
  • 42,633
  • 14
  • 77
  • 146
5

It depends... Often on things not included in your example. For one thing, your entire property can be shortened to an auto-implemented property:

public string FirstName { get; set; }

Which would make the question moot in this case. Beyond that, the question comes down to what sort of logic may exist (now or in the future) in the property and whether or not that logic needs to be invoked by the constructor.

For example, does the property internally check for a required value or perform some other validation? Something like this:

private string firstName;
public string FirstName
{
    get { return firstName; }
    set
    {
        if (string.IsNullOrWhiteSpace(value))
            throw new ArgumentNullException("FirstName");
        firstName = value;
    }
}

In a case like this clearly you'd want the constructor to use the property and not the backing field so that the logic is applied when constructing the object.

Conversely, you might have logic that should only be used when accessing the setter but not when constructing the object. Off the top of my head one example might be an object which maintains information about a Location. It might have an Address property and a Coordinates property, and any time one of them changes there is a back-end process to geolocate the new value and update the other. But you might have a constructor which accepts both (perhaps when re-building an existing Location from a database) and it wouldn't make sense to perform the geolocation during construction. In that case you'd set the backing fields and not the properties.

For lack of a compelling reason not to use the properties, I'd generally prefer to use them instead of the backing fields. Simply because logic might be added to those properties later that all accessors should use. I also find it more likely that the properties have a more meaningful name than backing fields (for example, FirstName is more readable/meaningful than _firstName) so the preference would be to keep the rest of the code as readable as possible and to prefer more readable names.

David
  • 208,112
  • 36
  • 198
  • 279
0

It is a stylistic choice that doesn't really matter. Personally, I use the public property name, because I like to use auto properties, and that is the only option in that case. Using the public property keeps my code consistent.

Katie Kilian
  • 6,815
  • 5
  • 41
  • 64
0

When I am writing POCOs (Plain Old CLR Objects) where things are trivial, I go with this approach:

public class POCO
{
    public POCO()
    {
        Name = "Moo-Juice";
    }

    public string Name { get; set; }
}

In non-trivial cases where I actually need the member variable, I prefix it with _ (this helps in intellisense, believe me - and allows you to distinguish between members and locals):

public class NonTrivial
{
    private string _name;

    public NonTrivial()
    {
        _name = "Jon Skeet";  // He is non-trivial
    }
}

This way I avoid polluting my code with this. everywhere.

Moo-Juice
  • 38,257
  • 10
  • 78
  • 128
0

It depends:

 private string firstName;
 public string FirstName
 {
    get
    {
        return firstName;
    }
    set
    {
        firstName = (value=="mycheck")?"default":value;
    }
 }

If your property has some validations then you should go for:

 public Student (firstName)
 {
     FirstName = firstName;
 }
Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110
0

The most common is to use the property, but it is a matter of choice.

In this case particularly, you should use automatic property:

public string FirstName { get; set; }

And the compiler adds the backing field automatically.

You can also choose to not add the parameter constructor, as since C# 3.5 (IIRC), you can use automatic initializers:

new Studant() { FirstName = "John Doe" }

Which calls the constructor, and sets the property in one line.

Overall, I tend to only request a constructor parameter for things it really depend on (see: dependency injection), and let the not always needed ones optional until they are required, like validating before persisting.

Ortiga
  • 8,455
  • 5
  • 42
  • 71