Introduction and Definitions
What do I mean by clean and usable library classes? By this, I mean one that will plug into a .Net Core application with a minimum of fuss. The type will be usable as a property, as a return from a method, parameter, as part of a model in an MVC application, or used as part of a database in an Entity Framework project.
These goals have implications on what we include as well as what we don’t include in the class. Things that must be on the included list are public properties that can be interpreted by both the MVC library and the Entity Framework library. This requirement means no enumerator or user-defined struct types. System defined structs or classes only. Also, the classes must include a default constructor if they have any constructor at all. Since typically anything I put into a library is going to be complex enough to need more than one constructor, it will require a default constructor. Last, unless the accessor properties return objects or System defined structs (i.e., base types, int, float, etc.), these properties will need attributes telling Entity Framework not to use them. Along with other properties that turn their values into something EF can use that has both getters and setters.
Other than the Entity Framework implications, the idea of clean, usable library classes should cover being able to be used transparently in the various collection types. What this means is overriding the Equals(object) and GetHashCode() methods so that they return valid values for the class. I also like to override at least a subset of the ToString() methods so I can get reasonable values rather than just the type name of the object as the default method returns.
There are other operators or methods that I add, override, or extend depending on the type of class I am writing for the library. For example, if the class is used in mathematical operations, I will always write extension methods for the arithmetic operations, comparison operators, Min, Max, Abs, and Square Root methods because these operations are expected for anything math-related.
One thing to note, my example in this article is based heavily on the existing .Net Core vector3 class. There are two reasons for this, first vector3 is an excellent…