- C# 7 and .NET Core 2.0 Blueprints
- Dirk Strauss Jas Rademeyer
- 337字
- 2025-02-25 23:58:46
Abstract classes
Open up the BaseClasses folder and double click on the Player.cs file. You will see the following code:
namespace cricketScoreTrack.BaseClasses { public abstract class Player { public abstract string FirstName { get; set; } public abstract string LastName { get; set; } public abstract int Age { get; set; } public abstract string Bio { get; set; } } }
This is our abstract class. The abstract modifier in the class declaration and the properties tells us that this thing we are going to modify has missing or incomplete implementation. It, therefore, is only intended for use as a base class. Any member marked as abstract must be implemented by classes that are derived from our Player abstract class.
The abstract modifier is used with:
- Classes
- Methods
- Properties
- Indexers
- Events
If we had to include a method called CalculatePlayerRank() in our abstract Player class, then we would need to provide an implementation of this method in any class that is derived from Player.
Therefore, in the Player abstract class, this method would be defined as follows:
abstract public int CalculatePlayerRank();
In any derived classes, Visual Studio 2017 will be running code analyzers to determine if all the members of the abstract class have been implemented by the derived classes. When you let Visual Studio 2017 implement the abstract class in a derived class, it is defaulted with NotImplementedException() in the method body:
public override int CalculatePlayerRank() { throw new NotImplementedException(); }
This is done because you haven't actually provided any implementation for the CalculatePlayerRank() method yet. To do this, you need to replace throw new NotImplementedException(); with actual working code to calculate the rank of the current player.
Abstract classes can be seen as a blueprint of what needs to be done. The way you do it is up to you as a developer.