Reputation: 17055
Please, help me with to understand this piece of code:
protected Customer()
{
}
in the following class (Model class from sample WPF MVVM app):
public class Customer : IDataErrorInfo
{
#region Creation
public static Customer CreateNewCustomer()
{
return new Customer();
}
public static Customer CreateCustomer(
double totalSales,
string firstName,
string lastName,
bool isCompany,
string email)
{
return new Customer
{
TotalSales = totalSales,
FirstName = firstName,
LastName = lastName,
IsCompany = isCompany,
Email = email
};
}
protected Customer() // it is what I asked about
{
}
#endregion // Creation
......
}
Upvotes: 1
Views: 268
Reputation: 12401
Using the protected
keyword on the constructor only allows instantiation of the Customer
object inside itself (like the static factory methods) and inside any class that derives from Customer
.
Upvotes: 1
Reputation: 15335
The piece of code you point at is a constructor. It is a method that (potentially) gets automatically invoked whenever an instance of your class is created at runtime.
In this case, it is marked with the protected
keyword. This means that only the owner class plus any derived classes (i.e. classes that inherit from it) have access to it.
By looking at your code, the two versions of the CreateNewCustomer()
static method in your class create instances of the class, invoking the constuctor. By making the constructor protected, the code guarantees that the class retains exclusive control over instantiation; this means that no other code outside the class (or its descendant classes) can create instances of this class.
Upvotes: 3
Reputation: 12857
This means that the constructor for your class has "protected" access, meaning that only members of this class or subclasses can call it. Practically, this means that either a static method is being used to create an instance of this class, or that another constructor (possibly in a derived class) is delegating to this constructor.
Upvotes: 1
Reputation: 4992
protected Customer() { }
is a constructor, a special method that automatically gets called when you instantiate an object from a class. When you type Customer c = new Customer()
, the constructor is allowed to initialize that instance after the run-time has allocated and reset memory for it. The protected
keyword means that only code inside the class Customer
or of its descendants are allowed to instantiate said class using that specific constructor.
Upvotes: 4
Reputation: 2593
The constructor is protected so that only the static creation methods can actually instantiate the class.
Upvotes: 2