Classes

Adding a constructor to a class

So, in our previous examples we've added methods and properties to our class,  Person . Typically when you define a class, you need to ensure that it can be initialized in a useable state. That being, when you use the  new  statement, you should be able to provide it any arguments it needs to be usable straight after. You achieve this through something known as a constructor.

using System; public class Person { ...

 

Remember in our previous concepts we mentioned the  default constructor . All classes are provided a default constructor if you do not add any constructors explicitly in your code. Let's define our cosntructor. What we want our constructor to do is allow us to pass in the name of our person. So it starts with a declaration, but this time we don't provide the constructor with a name, we simply say:

public Person

We use the  public  keyword to tell the compiler that we should be able to allow external callers the ability to create instances of  Person  with this constructor. We also provide the type, in this case it has to match  Person  because the constructor returns a new instance of our  Person  class. Next up, we need to define a pair of parenthesis  (  and  )  which allows us to specify constructor arguments, and within those parenthesis we add our variables, in this case, two variables named  firstName  and  lastName , separated by a comma.

public Person(string firstName, string lastName) 

We follow that up with our braces  {  and  } . The last thing to do, is to assign our variable value to our  Name  property:

FirstName = firstName;
LastName = lastName;

 

Page 12 of 20