I feel like this should have been explained on page 1 of lesson 1 somewhere, but either it wasn't or I missed it.
If there is the following class:
class Person
{
public string name {get; set;}
public int age {get; set;}
}
Then later I do this:
Person myUncle = new Person();
Why do I need that first Person at the start?
I know I am creating a new object of type "Person" that is called "myUncle".
Why do we have that Person at the start? Could a new Person(); object be something else?
Every tutorial / book whatever I have seen just rolls right through this part with the author saying "ok now we make a new instance this way..." but never explains why the syntax is like this.
The left side declares a variable of type Person.
The right side creates an object of type Person.
The = assigns the object on the right the variable on the left.
You might ask, why can't C# figure out what variable type I want?
The answer is, it can:
var myUncle = new Person();
However, there are situations where you might want to declare the type explicitly.
This is a slightly contrived example, but suppose I had a new class which is a subclass of Person.
class Child : Person
{
public bool isChildish {get; set;}
}
I might could then declare a variable of type Person to hold an object of type Child.
Person myUncle = new Child();
Now, the Person on the left looks less redundant.
Update: One reason why you might want Person myUncle over var myUncle is because you can separate declaration from initialization.
The following code will compile:
Person myUncle;
myUncle = new Person();
The following code will not compile;
var myUncle;
myUncle = new Person();
A way I like to think about it is like this: The right hand side is what the object "actually is" and the left hand side, is what you will be "telling" other parts of your application the object is. So in the basic example like yours, you are creating a Person and telling the rest of your application that this is a Person object, but you don't always have to reveal exactly what your object is. For example:
Person p1 = new Doctor();
Person p2 = new Teacher();
IService s = new ServiceImpl();
IEnumerable<Person> personEnum = new List<Person>();
In the first two examples you are creating two objects doctor and teacher which inherit from Person, but any part of your application that is passed p1 or p2 will only know it is a Person object. In the third example, the object is actually of type ServiceImpl, but the rest of your application will only know that this is an object that implements the IService interface.
The point of all of this is to keep your application loosely coupled, by only revealing as much as you need to about the actual objects.
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