Customer cust = new Customer();
Customer
is a class. cust
is an assigned name. I'm not sure what Customer()
does...
What does this line do? Why do we need it? Isn't having Customer
and Customer()
a bit repetitive?
It creates a new instance of Customer()
and assigns a reference to the newly created object to the variable cust
.
If you want to remove the repetition and you're using C# 3.0 or later and it's a local variable, you can use:
var cust = new Customer();
That has exactly the same meaning - it's still statically typed, i.e. the variable cust
is still very definitely of type Customer
.
Now, it happened to be repetitive in this case, but the two Customer
bits are entirely separate. The first is the type of the variable, the second is used to say which constructor to call. They could have been different types:
Customer cust = new ValuedCustomer();
IClient cust = new Customer();
object cust = new Customer();
etc. It's only because you created an instance of exactly the same type as the type of the variable that the repetition occurred.
It declares a Customer and then initializes it.
Customer cust; //declares a new variable of Customer type
cust = new Customer(); //Initializes that variable to a new Customer().
new creates the actual object, cust hold's a reference to it.
The empty parentheses indicates that the construction of the Customer object is being passed no parameters, otherwise there would be a comma separated list of parameters within the parenthesis.
Customer() is the constructor method on the Customer class. If you're bothered by the repetition, you can use a implicit variable declaration:
var cust = new Customer();
The first Customer defines the datatype of the cust variable. The new Customer()
part creates an instance of the Customer class and assigns it to the variable.
It is not required however that the datatype be Customer
. If you have the Customer class inherit a different class (say Person) or an interface (say IPayer), you could define it as
Person cust = new Customer();
IPayer cust = new Customer();
This is one of the basic principles of Polymorphism in object-oriented programming.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With