Classes

Putting it all together

Now we should be able to call our constructor by putting this all together:

using System; public class Program { ...

 

This is a simple example of how to add functionality and encapsulate state with our classes. We could flesh this out by adding additional properties, methods or constructors:

public class Person
{
    public Person()
    {

    }

    public Person(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public int Age { get; set; }

    public string GetFullName()
    {
        return FirstName + " " + LastName;
    }

    public int GetYearOfBirth()
    {
        return DateTime.Now.AddYears(-Age).Year;
    }
}

With our fleshed out example above, we've defined two of each construct. Two constructors:

public Person() { }
public Person(string firstName, string lastName) { }

This allows us to create instances of our  Person  class two ways:

new Person();
new Person("John", "Smith");

We've also added an extra property:

public int Age { get; set; }

This will allow us to set a person's age. We've then added an additional method,  GetYearOfBirth  which allows us to read the person's year of birth (in a very simplistic way):

public int GetYearOfBirth()
{
    return DateTime.Now.AddYears(-Age).Year;
}

You can add additional properties, methods and constructors to your classes, depending on your use cases and problems.

Page 14 of 20