Hi Harrison,
Just to add to Gary’s most excellent reply, specifically on the new keyword you queried.
The new
keyword is used to instantiate a new instance of an object.
To give you an analogy…
You could think of a class as a cookie cutter, when you use new it’s like pushing the cookie cutter into the dough, you create an object (the cookie), and it’s in the shape of the cookie cutter you used.
Each object (an instance the class) will have the same structure as the class, the same variables (fields), properties and methods, but the data that each object holds may be different. Using the cookie analogy, the shape of the cookie would be the same, but perhaps the cookie has a frowny face, or a smilie face, blue eyes, or white eyes, two gummy buttons, or one gummy button…Here’s a non cookie example;
public class Person
{
// member variables (fields)
private string _name;
private int _age;
// constructor
public Person()
{
// ...
}
// properties
public string Name
{
get { return _name; }
set { _name = value; }
}
public int Age
{
get { return _age; }
set { _age = value; }
}
// methods
public void Walk()
{
// ...
}
public void Run()
{
// ...
}
public void Jump()
{
// ...
}
}
The above may introduce some things you are not familiar with yet, specifically the constructor and the properties, but the above is a template, our cookie cutter. We’ve called it Person, each time I use it I can create a new object of type Person, the data that I store in each Person can be different.
Person securityGuard = new Person();
Person bankManager = new Person();
In the above, I have created two objects, two instances of the Person type. Using new
made a call to the class’s default constructor, now lets make them more unique;
securityGuard.Name = "Harrison";
securityGuard.Age = 21;
In the above I use the properties to set both the name and the age, in doing so it uses the set
block of code to store the value I have passed it into the appropriate member variable, so in the case of “name”, the Name property sets the _name
member variable, and in the case of “age”, the Age property sets the _age
member variable.
Finally, we have defined some behaviour in our class, methods Walk, Run and Jump, so we could then use these behaviours by making a call to them via our object;
bankManager.Jump();
securityGuard.Run();
Note, I have deliberately left our any code from the “middle” of these methods, what they do would be up to you
I’ve linked some further reading below for you, don’t worry too much if it doesn’t all make sense right away, but hopefully some of it will be familiar from concepts you’ve already seen and used in the course.
Hope this helps
See also;