Skip to content

Kernix13/csharp-oop-class-syntax

Repository files navigation

Introduction to Object-Oriented Programming (OOP)

This project uses various Object-Oriented Programming concepts and syntax such as classes, fields, properties, and constructors.


Installation & Usage

  1. Clone this repository and switch into project folder

    git clone https://github.com/Kernix13/csharp-oop-class-syntax.git AnimalShelter
    cd AnimalShelter
  2. Run the application

    dotnet run
  3. Build the application

    dotnet build

Quick Start

git clone https://github.com/Kernix13/csharp-oop-class-syntax.git AnimalShelter
cd AnimalShelter
dotnet run

Note

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


Class syntax used

I used the following syntax/keywords in this project:

  1. namespace
  2. using
  3. public class
  4. public field
  5. public static field
  6. private field
  7. private static field
  8. public properties with get, set accessors
  9. public property with private set;
  10. public property with modern syntax: { get; set; }
  11. public property with the longer/verbose syntax
  12. public property with validation
  13. Use of expression body definition => in property accessor
  14. 1 Static constructor
  15. 1 Public instance constructor with parameters
  16. 2 optional parameters in instance constructor
  17. 2 named arguments used in Program.js
  18. 2 public methods with the return keyword
  19. 1 public void method
  20. Partial class (weak implementation)
  21. new keyword to create objects from the classes


Class syntax NOT used

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.

My to-do list to learn or add to projects

  1. readonly access level: how does this differ from private set;?
  2. params method keyword
  3. The this keyword in methods to access fields, properties, and methods of the current instance (Add later)
  4. Extension methods: this ClassName paramName
  5. abstract modifier

Skip learning for now

  1. The init accessor
  2. protected access level
  3. required access level
  4. internal access level
  5. The ref or out keywords
  6. The field keyword: You must set your <LangVersion> element to preview in your project file in order to use the field contextual keyword. What is @field?
  7. Static classes - unsure about this one
  8. Nested classes - don't do this one
  9. Partial members - don't do this one
  10. Object initializers?
  11. Copy constructors?
  12. Class finalizers?

Other points

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.


Important notes

  1. Static fields are accessed using the class name, not the instance name
    • For example: Adoption.AdoptionFee ✔️ vs pet1.AdoptionFee
  2. The this keyword is not available in a static constructor
  3. Properties combine aspects of both fields and methods
  4. The keyword value represents the value being assigned to the property (what is passed to the class constructor during instantiation I think)


Questions

  1. Why exactly do I need to use namespace?
    1. So that I can use the classes in all files?
    2. Is it similar to import/export syntax in ES Modules or it that what partial does?
  2. Can I use using AnimalShelter; instead of namespace AnimalShelter;? (Try it and see)
  3. What is garbage collection and is it important to know or is it an automatic thing to just be aware of?
  4. What is the difference between field vs. property?
    1. 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?


Code: line-by-line

Examples and descriptions for the code I used.

Pet.cs

NAMESPACE

  • I removed this from Program.cs and the app crashed
  • This line says, "This class lives inside AnimalShelter"
namespace AnimalShelter;

CLASS + PARTIAL

  • 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 {}

FIELD MODIFIERS

  • 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; }

PROPERTIES

  • 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;
   }
}

CONSTRUCTOR

  • 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 new operator or a base statement
  • 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) {}

METHOD

  • public void: basic method that does not return a value
// 1.
public void DisplayInfo() {}


PetMethods.cs

NAMESPACE

  • This is needed here as well
namespace AnimalShelter;

CLASS + PARTIAL

  • The keyword partial is 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 partial keyword brings the code into Pet.cs so that is not necessary.
public partial class Pet {}

METHOD

  • Nothing special here - 1 method that returns a value and 1 void method
// 1.
public string GetPetDescription() {}

// 2.
public void UpdateAge(float newAge) {}


Adoption.cs

NAMESPACE

  • This is needed here as well
namespace AnimalShelter;

FIELD MODIFIERS

  • private static, public, and public static similar 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; }

CONSTRUCTOR

  • A single instance constructor
public Adoption(string adopterName, Pet adoptedPet, int adoptionFee) {}


Program.cs

USING

  • This is the only file that needs this code
  • namespace is not needed in this file unlike the other files.
  • Program.js has to use a "Visitor's Pass" (the using statement) to reach inside and talk to the classes living there
using AnimalShelter;

NEW

  • Just like in JavaScript, the new keyword is needed to create class instances (objects)
// 1.
Pet pet1 = new Pet(pet1Name, pet1Species, pet1Age);

// 2.
Pet pet2 = new Pet(pet2Name, pet2Species, pet2Age);

STATIC FIELD

  • Static Member Access: Accessed using the Class Name (Pet and Adoption) instead of an object name, because the data belongs to the blueprint itself
// 1.
Pet.TotalPets

// 2.
Adoption.AdoptionFee

About

C# object oriented programming syntax for classes, fields, properties, constructors and methods.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages