CSharp Learning Outline TextbookStyle
CSharp Learning Outline TextbookStyle
Style
Chapter 3: Object-Oriented Programming in C#
Defining Properties
class Person
{
private string name; // Private field
In this example:
Auto-Implemented Properties
class Person
{
public string Name { get; set; } // Auto-implemented property
public int Age { get; private set; } // Read-only property
}
Read-Only Properties
class Car
{
public string Model { get; }
public string Make { get; }
Computed Properties
class Rectangle
{
public double Width { get; set; }
public double Height { get; set; }
// Computed property
public double Area
{
get { return Width * Height; }
}
}
Static Fields
class Employee
{
public static int employeeCount = 0;
public Employee()
{
employeeCount++; // Increment static field for each new object
}
}
Static Methods
class MathUtility
{
public static int Add(int a, int b)
{
return a + b;
}
}
3.9 Namespaces
Namespaces in C# are used to organize code and avoid name conflicts. A namespace
provides a way to group related classes, interfaces, and other types.
Defining a Namespace
namespace Company.Project
{
class Employee
{
public string Name { get; set; }
}
}
struct Point
{
public int X;
public int Y;
Example of an enum:
enum DayOfWeek
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
Exercises
Exercise 1: Static Members
Create a Book class with a static field bookCount that keeps track of how many Book objects
are created. Each time a new Book is instantiated, increase the bookCount by one.