Implementing Functionality Using Methods

Learn about implementing functionality in C# using both instance and static methods.

Think of some methods that would apply to a Person instance that could also become operators like + and *. What would adding two people together represent? What would multiplying two people represent?

The obvious answers are getting married and having babies. We might want two instances of a Person to be able to marry and procreate. We can implement this by writing methods and overriding operators.

Instance methods are actions an object does to itself. Static methods are actions the type does. Using static and instance methods to perform similar actions often makes sense. For example, the string has a Compare static and CompareTo instance methods. This puts the choice of how to use the functionality in the hands of the programmers using our type, giving them more flexibility.

Implementing functionality using methods

Let’s start by implementing some functionality by using both static and instance methods:

Step 1: In PersonAutoGen.cs, in the Person class, add read-only properties with private backing storage fields to indicate if that person is married and to whom, as shown in the following code:

Get hands-on with 1400+ tech skills courses.