dmt37

For some reason I remember reading that it is not considered best practice to set a Property within the constructor when there is a private variable associated with said property. It would be considered best practice to go ahead and set the private variable. Is this true for example:

public class MasterItem : Item

{

internal MasterItem( int facilityId ) : base( null )

{

this.Facility= (Facility)facilityId;

}

protected Facility facility;

public Facility Facility

{

get { return facility; }

set { .... facility = value .... }

}

}

The issue is that I have more going on in my set method of the property that I need to be run when the facility is set via the constructor. Obviously, the easiest way to do this is to reference the property in the constructor. Is this not considered best practice Or is my question irrelevant



Re: Visual C# General Best Practice: Properties in the Constructor

OmegaMan

Of course one's rule of thumb may not apply to all...but I see nothing wrong with setting properties via a constructor. One is setting up the object for processing and there should be nothing wrong with that. Just don't use the property in one case then the actual variable...be consistent.

The only issue that could impede that is if  processing is done in the property, or another method call for that matter, that originates from the constructor, that could throw an exception. Some consider the throw of an exception from a constructor to be a no-no...so if setting a property involves processing code and one wants to adhere to that rule, then no don't do it. <g>







Re: Visual C# General Best Practice: Properties in the Constructor

David Troyer

Ahhh yes, point taken. Considering constructors in the rest of the code do all sorts of exception throwable calls, I doubt anyone will call me out on this one.