Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C#, what does "Customer cust = new Customer();" do?

Tags:

c#

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?

like image 681
user133466 Avatar asked Jul 28 '09 23:07

user133466


4 Answers

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.

like image 165
Jon Skeet Avatar answered Sep 24 '22 17:09

Jon Skeet


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.

like image 42
daniel Avatar answered Sep 22 '22 17:09

daniel


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();

like image 37
Jon Galloway Avatar answered Sep 22 '22 17:09

Jon Galloway


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.

like image 34
Chetan S Avatar answered Sep 22 '22 17:09

Chetan S