Classes, Fields, Methods and Constructors

Classes, Fields, Methods and Constructors

Classes

As briefly explained in a previous tutorial, classes are a very common way of defining custom types. Classes are reference types.

A class can be defined by using the keyword ‘class’ followed by the name you wish for the class to have. As a naming convention, class names should be written in upper camel case.

You may also want to use an access modifier in conjunction with classes to dictate what elements of your code can utilise the class.


using System;

public class Program
{
	public static void Main()
	{
		Car car1 = new Car(20);
		Console.WriteLine(car1.horsePower);
	}
}

public class Car
{
	public int horsePower;

	public Car(int horsePower)
	{
	    this.horsePower = horsePower;
	}
}
                

A class can have a number of members which can take the form of

  • Properties
  • Methods
  • Indexers
  • Events
  • Fields
  • Overloaded Operators

Fields / Member Fields

Fields are variables that belong to classes. A number of modifiers can be used in conjunction with fields.

The static modifier dictates whether an instance (object) of that class needs to be created in order to use the member, or if it can be used statically.


                    using System;

public class Program
{
	public static void Main()
	{
		Car car1 = new Car();
		Car car2 = new Car();
		Console.WriteLine(Car.carSales);
	}
}

public class Car
{
	public static int carSales;

	public Car()
	{
	    carSales++;
	}
}
                

Here we can see that as the carSales field is static, it cannot be accessed by an instance of Car, instead, its values are shared between all Cars. Every time we call the constructor of Car, the value of carSales will increment.

The four types of access modifiers can also be applied to Fields, we covered these in an earlier tutorial.

Using the Read-only modifier will prevent a field from modification after it is initialised.

Initialising Fields

If a value is not provided for a field, it will take on the default value for that type when the object is created. For example, if you have an integer field that does not have a default value specified for it, then it will take on a value of 0. For reference fields, the default value will be null.

Fields will be initialised before the constructor is executed.

To reduce the amount of code you have to write, if you have multiple fields that have the same type and modifiers, they can be declared in a comma-separated list.


                    using System;

public class Program
{
	public static void Main()
	{
		Car car1 = new Car(20, 4);
		Console.WriteLine(car1.horsePower);
	}
}

public class Car
{
	public int horsePower, numberOfWheels;

	public Car(int horsePower, int numberOfWheels)
	{
	    this.horsePower = horsePower;
		this.numberOfWheels = numberOfWheels;
	}
}

                

Methods

A method is a function that belongs to a class or instances of a class. A method performs an action via a collection of statements.

Class methods

Information can be provided to a method by means of parameters and output information back to its caller via return values. Some methods may be labelled as void, this means there is not a return type and the action does not return a result – these methods do not contain the return keyword.


                    using System;

public class Program
{
	public static void Main()
	{
		Car car1 = new Car(20, 4);
		Console.WriteLine(car1.getNumberOfWheels());
	}
}

public class Car
{
	public int horsePower, numberOfWheels;

	public Car(int horsePower, int numberOfWheels)
	{
	    this.horsePower = horsePower;
		this.numberOfWheels = numberOfWheels;
	}

	public string getNumberOfWheels()
	{
		return $"This car has {numberOfWheels} Wheels";
	}

}
                

The signature of a method must be unique within the context of the type. A signature is the combination of the methods name as well as the parameters. If there is a different combination of parameters between two classes with the same name – they are each considered to be unique. We will look into this later.

Similar to fields, methods allow for many modifiers.

Modifier Type Keyword
Access public internal private protected
Inheritance new virtual abstract override sealed
Partial partial
Static static
Unmanaged unsafe extern
Async async

Expression-bodied Members

Sometimes methods do not need to be more than one statement, in such circumstances expression-bodied methods can be used (as of C# 6). The braces and return statement are replaced with an arrow.


                    using System;

public class Program
{
	public static void Main()
	{
		Car car1 = new Car(20, 4);
		Console.WriteLine(car1.getNumberOfWheels());
	}
}

public class Car
{
	public int horsePower, numberOfWheels;

	public Car(int horsePower, int numberOfWheels)
	{
	    this.horsePower = horsePower;
		this.numberOfWheels = numberOfWheels;
	}

	public string getNumberOfWheels() => $"This car has {numberOfWheels} Wheels";

}
                

You can learn more about expression-bodied members at Microsofts C# documentation

Overloading Methods

As mentioned earlier – it is possible for a class to have multiple methods with the same name permitting that they have a different set of parameters. This is called overloading methods.

The overloaded methods must have a different set of parameters as just changing the name of the parameters will not allow the compiler to differentiate between the methods.

Local Functions

C# 7.0 and later versions allowed for local functions to be used. These are functions defined within further functions. Local functions make it clear that the method isn’t used anywhere else but within the containing function.

It is not possible to define a local function within expression-bodied members.

All of the members in the outer function can be accessed within the inner function.

Constructors

When an instance of a class is created, it runs a series of initialisation statements. These statements may have a specific purpose such as setting up member fields. The collection of initialisation statements is called the constructor.

The constructor is a member method that has the same name as the class and no return type. The constructor can take a number of arguments that can be passed in parenthesis when the object is created.

Just like normal member methods, constructors can be overridden by using the same method name but with different parameters.

If there is not a constructor defined for a class, the compiler will automatically generate a parameterless constructor. As soon as you implement a custom constructor the default one is no longer available to use and will need to be redefined.