Lecture Topics:
new
override
Lab:
Static members belong to the class itself rather than an instance, shared across all instances of the class.
Static Fields:
Shared data accessible without instantiating the class.
Example:
public class Employee
{
public static int EmployeeCount; // Shared field
public string Name { get; set; }
public Employee() => EmployeeCount++; // Increment on creation
}
Employee emp1 = new Employee();
Employee emp2 = new Employee();
Console.WriteLine(Employee.EmployeeCount); // Outputs: 2
Static Methods:
Methods that don’t require an instance, often used for utility functions.
Example:
public class Calculator
{
public static int Add(int a, int b) => a + b;
}
Console.WriteLine(Calculator.Add(5, 3)); // Outputs: 8
Static Properties:
Properties that belong to the class, not instances.
Example:
public class Settings
{
private static string _companyName = "Acme Corp";
public static string CompanyName
{
get => _companyName;
set => _companyName = value;
}
}
Settings.CompanyName = "New Corp";
Console.WriteLine(Settings.CompanyName); // Outputs: New Corp
Static Constructors:
Initialize static members, called automatically before any static member is accessed.
Example:
public class Logger
{
public static string LogFilePath;
static Logger()
{
LogFilePath = "log.txt";
Console.WriteLine("Static constructor called");
}
}
Console.WriteLine(Logger.LogFilePath); // Outputs: Static constructor called, log.txt