Classes - mcbride-clint/DeveloperCurriculum GitHub Wiki
Overview
Objects are the lowest level building blocks of .Net.
Everything inherits from the Object
base Type.
A Class is a definition of a type and it's behaviors.
Classes are always passed by reference between functions and an instance of the class is null
until it is initialized.
- Note: Structs are another type of Object that are passed by value.
A class is meant to encapsulate a single idea/concept such as a business process or business object. It will encapsulate fields, properties, and methods that will accomplish that concept.
public class User { // basic definition of a class. By default it has not additional functionality over Object
// Fields, properties, and methods go here...
}
...
User user; // null instance of user
user = new User(); // initializes user with a new instance of User
Constructor
A classes constructor allows for you to specify logic that will occur upon the object's initialization as well as allow for dependencies or required initial data to be passed in. Once parameters are created for a constructor then a parameterless initialization is no longer valid.
Required Data Example
public class User {
public User(string firstName, string lastName){ }
}
...
// initializes userInstance with a new instance of User with first name of "John" and a last name of "Smith"
User userInstance = new User("John", "Smith");
// this is a compilation error
User otherUser = new User();
Dependency Example
In the case of a behavioral/business process object then it can be extremely useful to pass in the dependencies for a class to further isolate it's concerns. This helps for testing and flexibility of code.
For a rough example, pretend that the user class has a method that uses the current date to determine which set of business rules to follow.
If the System.DateTime.Now
class is used to get the current date then the code would likely work correctly in production but testing the different code paths would be difficult.
The code path that executes on the weekend would never be able to be tested on a weekday.
If the class allowed for another object to be passed in then the code be tested being given many different values.
Two options that could be passed in could be a DateTime
object that just contains the current date or an Interface that was in charge of providing a DateTime
when needed, such as ICurrentDateTimeProvider
. (This is a poor example of needing this as it probably shouldn't be the User class's responsibility to accomplish this)
More information on this can be found in Interfaces and Dependency Injection.
public class User {
private DateTime _currentDate;
public User(DateTime currentDate){
// Save currentDate in a field for later use
_currentDate = currentDate;
}
public User(ICurrentDateTimeProvider currentDateProvider){
// Save current date from the provider in a field for later use
_currentDate = currentDateProvider.CurrentDate;
}
}
// A ICurrentDateTimeProvider, in this case, can be implemented by any class that has a read only property of CurrentDate
public Interface ICurrentDateTimeProvider {
DateTime CurrentDate { get; }
}
Fields and Properties
Classes are able to contain data in either fields or properties.
- Additional Details - https://docs.microsoft.com/en-us/dotnet/csharp/properties
Fields
Fields are variables that are designed to be specific to the class that they are declared in.
Usually scoped to be private
, they contain variables that are shared throughout the class.
They are useful for storing values passed in via a constructor to be held until needed by another method.
Usually named starting with an underscore private DateTime _currentDate;
Properties
Properties, similar to fields, are used to retain data within the scope of the class but have a few additional features.
- Can be inherited by child classes through Inheritance.
- Can be enforced by Interfaces.
- Can have additional getter and setter logic.
Behind the scenes, properties use a generated backing field to hold the value.
Usually named starting with an Uppercase Letter public DateTime CurrentDate { get; set; }
Getter and Setter
The declaration of properties has changed through versions of .Net. Initially, the developer had to fully specify the full getter, setter, and backing field logic. Auto-Properties were created to create cleaner code when handling basic Properties. Expression Bodied was created to further simplify readonly getter only Properties. This syntax is essentially a function that will be called whenever the property is accessed.
// Traditional Property with backing field
private DateTime _storedDate ;
public DateTime StoredDate {
get {
return _storedDate ;
}
set {
_storedDate = value;
}
}
// Auto-Property
public DateTime StoredDate { get; set; }
// Getter Only Expression Bodied Property
public DateTime CurrentDate => DateTime.Now;
// Expression Bodied Property with backing field
private DateTime _storedDate ;
public DateTime StoredDate {
get => _storedDate;
set => _storedDate = value;
}
Repo Programming Examples:
- 1-Framework-Core-Standard -
PaSalesTaxCalculator
- 2-C#-Basics
See Also
- .Net Common Type System - https://docs.microsoft.com/en-us/dotnet/standard/base-types/common-type-system
- Classes C# Programming Guide - https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/classes
- Pluralsight - Introduction to the C# Type System - https://app.pluralsight.com/library/courses/introduction-c-sharp-type-system/table-of-contents
- Pluralsight - C# Fundamentals: Working with Classes and Objects - https://app.pluralsight.com/course-player?clipId=1acccfd3-3a64-4719-9bbb-8dc3a43b1c64