This project uses various Object-Oriented Programming concepts and syntax such as classes, fields, properties, and constructors.
-
Clone this repository and switch into project folder
git clone https://github.com/Kernix13/csharp-oop-class-syntax.git AnimalShelter cd AnimalShelter -
Run the application
dotnet run
-
Build the application
dotnet build
git clone https://github.com/Kernix13/csharp-oop-class-syntax.git AnimalShelter
cd AnimalShelter
dotnet runNote
There are variables used to create 2 pet objects in Project.cs. Those objects are what creates the output in the console. I could create ReadLine statements and output the results, but you would only see one object in the console.
Console output:
$ dotnet run
Pet class initialized
New pet: Buddy, Pet id: 1, Species: dog, Breed: AmStaff, Pet Age: 1.5
New pet: Luna, Pet id: 2, Species: cat, Breed: DSH, Pet Age: 12
New pet: Logan, Pet id: 3, Species: dog, Breed: unknown, Pet Age: 3
Total pets in shelter: 3
Adoption ID: 1, Adopter Name: Jim, Adopted Pet: Luna, Adoption Fee: $100
Pet ID: 3, Name: Logan, Age: 3, Species: dog, Breed: unknown
I used the following syntax/keywords in this project:
- namespace
- using
public classpublicfieldpublic staticfieldprivatefieldprivate staticfield- public properties with
get,setaccessors - public property with
private set; - public property with modern syntax:
{ get; set; } - public property with the longer/verbose syntax
- public property with validation
- Use of expression body definition
=>in property accessor - 1 Static constructor
- 1 Public instance constructor with parameters
- 2 optional parameters in instance constructor
- 2 named arguments used in Program.js
- 2 public methods with the
returnkeyword - 1 public void method
- Partial class (weak implementation)
newkeyword to create objects from the classes
I did not, or decided not to, use the following due to the fact I did not understand them or did not see a way to work them in.
readonlyaccess level: how does this differ fromprivate set;?paramsmethod keyword- The
thiskeyword in methods to access fields, properties, and methods of the current instance (Add later) - Extension methods:
this ClassName paramName abstractmodifier
- The
initaccessor protectedaccess levelrequiredaccess levelinternalaccess level- The
reforoutkeywords - The
fieldkeyword: You must set your<LangVersion>element to preview in your project file in order to use thefieldcontextual keyword. What is@field? - Static classes - unsure about this one
- Nested classes - don't do this one
- Partial members - don't do this one
- Object initializers?
- Copy constructors?
- Class finalizers?
I did not use arrays or Console.ReadLine or other C# syntax learned previously because there was so much to learn for this project. Later I could add an array of pet types (dog, cat, rabbit, etc) and use a ReadLine to grab the value and add it to Species in Pet.cs.
The following keywords and terms were covered in the lessons but I do not know what they are, how to use them, or when to use them:
struct,interface,enum,record,delegate
See oop.md for notes on all of the above.
- Static fields are accessed using the class name, not the instance name
- For example:
Adoption.AdoptionFee✔️ vspet1.AdoptionFee❌
- For example:
- The
thiskeyword is not available in a static constructor - Properties combine aspects of both fields and methods
- The keyword
valuerepresents the value being assigned to the property (what is passed to the class constructor during instantiation I think)
- Why exactly do I need to use
namespace?- So that I can use the classes in all files?
- Is it similar to
import/exportsyntax in ES Modules or it that whatpartialdoes?
- Can I use
using AnimalShelter;instead ofnamespace AnimalShelter;? (Try it and see) - What is garbage collection and is it important to know or is it an automatic thing to just be aware of?
- What is the difference between field vs. property?
- If you add some form of
{ get; set; }to a field, does that turns it into a property? If so, why/when use fields without that?
- If you add some form of
Examples and descriptions for the code I used.
- I removed this from Program.cs and the app crashed
- This line says, "This class lives inside
AnimalShelter"
namespace AnimalShelter;- I did not see the value of using partial classes. I can see how a class filled with many methods could be a problem.
- Is this similar to import/export syntax in JavaScript ES Modules?
public partial class Pet {}private: Hidden from all other classes; only accessible within this class.static: Belongs to the class itself; shared by all instances.private static: Accessible only inside the class; shared by all instances of that class.s_nextPetId: incremented for each new instance of Pet inside the instance constructor.
public: Visible to all project code; any class can see and change this.public static: Visible to all project code and shared as a single instance by the class.
/* PRIVATE + STATIC */
// 1.
private static int s_nextPetId = 1;
// 2.
private string _petName = "Unknown";
// 3.
private float _age;
/* PUBLIC + STATIC */
// 1.
public static int TotalPets { get; private set; }
// 2.
public int PetId { get; }
// 3.
public string Species { get; set; }- Backing Fields:
_petName,_age- marked private, the secret spot where the data is actually stored - The Property:
PetName,Age- marked public, the public "gatekeeper" that controls how data is read or changed - Private backing field: automatic when you use
{ get; set; } { get; private set; }: Anyone can read the value, but only this class can change it.{ get; }: Read-only - the value is set when the object is born and can never change.{ get; set; }: Full access; any part of the project can read or change this at any time.
// 1. MODERN SYNTAX
public static int TotalPets { get; private set; }
public int PetId { get; }
public string Species { get; set; }
// 2. OLDER/VERBOSE SYNTAX
private float _age;
public float Age
{
get { return _age; }
set { _age = value; }
}
// 3. VALIDATION
private string _petName = "Unknown";
public string PetName
{
get { return _petName; }
set
{
if (string.IsNullOrWhiteSpace(value))
_petName = "Unknown";
else
_petName = value;
}
}- public instance constructor: this builds the instance objects
- Constructors are declared using the same name as the class and doesn't include a return type
- The constructor's method signature can include an optional access modifier
- Once again: A constructor's method signatures doesn't include a return type
- Classes can have more than one constructor. When a class has more than one constructor, the constructors usually take different arguments
- Classes often define constructors that take parameters.
- Constructors that take parameters must be called using the
newoperator or abasestatement - static constructor: to initialize any static data, or to perform an action that needs to be performed only once
- A static constructor doesn't take access modifiers or have parameters
// 1. static constructor
static Pet() {}
// 2. public instance constructor - 1 version with params
public Pet(string name, string species, float age) {}- public void: basic method that does not return a value
// 1.
public void DisplayInfo() {}- This is needed here as well
namespace AnimalShelter;- The keyword
partialis needed in the "parent" class and is the partial files as well - they must match! - I forgot to add the fields and properties here and did not notice that it worked anyway.
- I assume the
partialkeyword brings the code intoPet.csso that is not necessary.
- I assume the
public partial class Pet {}- Nothing special here - 1 method that returns a value and 1 void method
// 1.
public string GetPetDescription() {}
// 2.
public void UpdateAge(float newAge) {}- This is needed here as well
namespace AnimalShelter;private static,public, andpublic staticsimilar to above- Custom Type Property: This property links the Adoption class to the Pet class
/* PRIVATE + STATIC */
// 1.
private static int s_nextAdoptionId = 1;
/* PUBLIC + STATIC */
// 1. read-only
public int AdoptionId { get; }
// 2.
public string AdopterName { get; set; }
// 3. Auto-Property Initializer
public static int AdoptionFee { get; set; } = 50;
// 4. Custom Type Property
public Pet AdoptedPet { get; set; }- A single instance constructor
public Adoption(string adopterName, Pet adoptedPet, int adoptionFee) {}- This is the only file that needs this code
namespaceis not needed in this file unlike the other files.Program.jshas to use a "Visitor's Pass" (theusingstatement) to reach inside and talk to the classes living there
using AnimalShelter;- Just like in JavaScript, the
newkeyword is needed to create class instances (objects)
// 1.
Pet pet1 = new Pet(pet1Name, pet1Species, pet1Age);
// 2.
Pet pet2 = new Pet(pet2Name, pet2Species, pet2Age);- Static Member Access: Accessed using the Class Name (
PetandAdoption) instead of an object name, because the data belongs to the blueprint itself
// 1.
Pet.TotalPets
// 2.
Adoption.AdoptionFee