20. object
An object in C# is a runtime instance of a class, containing its own unique state and behavior. When a class is defined, it serves as a template, but an object represents a concrete realization of that template in memory. Each object has its own set of values for the properties defined in its class.
For example, given a Person class:
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public void Introduce()
{
Console.WriteLine($"Hi, I'm {Name} and I'm {Age} years old.");
}
}
We can create multiple independent objects of this class:
Person person1 = new Person { Name = "Alice", Age = 30 };
Person person2 = new Person { Name = "Bob", Age = 25 };
person1.Introduce(); // Output: Hi, I'm Alice and I'm 30 years old.
person2.Introduce(); // Output: Hi, I'm Bob and I'm 25 years old.
Each object maintains its own copy of data, allowing for dynamic behavior in applications. Objects are managed in memory by the .NET garbage collector, which automatically deallocates unused objects. Understanding objects is essential for working with OOP principles such as encapsulation, inheritance, and polymorphism in C#.
21. field
A field is a variable that is declared inside a class or struct, representing the internal state or data of an object. Fields are used to store information relevant to an object, such as an entity's name, age, or status. Unlike properties, fields provide direct storage without encapsulation through accessors.
Example:
class Person
{
public string name; // Public field
private int age; // Private field
}
Fields can have different access modifiers (public, private, protected) that control their visibility. While fields can be used freely inside a class, it's considered best practice to use private fields with properties to control data access.
22. property
A property is a member that encapsulates a field by providing getter and setter accessors, ensuring controlled access to the data. Unlike fields, properties allow validation, transformation, and restrictions on how values are assigned or retrieved.
Example:
class Person
{
private string _name; // Backing field
public string Name
{
get { return _name; } // Getter
set { _name = value; } // Setter
}
}
Modern C# allows auto-implemented properties:
public string Name { get; set; }
Properties improve encapsulation, maintainability, and security compared to direct field access.
23. method
A method is a function defined inside a class or struct that performs a specific action. Methods define object behavior, such as calculating values, modifying state, or interacting with other objects.
Example:
class Calculator
{
public int Add(int a, int b)
{
return a + b;
}
}
Methods can have parameters, return values, and different access modifiers (public, private, protected). They support overloading, allowing multiple methods with the same name but different parameters.
24. constructor
A constructor is a special method that runs automatically when an object is created, used to initialize its fields and properties.
Example:
class Person
{
public string Name;
public Person(string name)
{
Name = name;
}
}
Constructors allow default values and prevent uninitialized objects. They can be overloaded to support multiple initialization scenarios.
25. destructor (finalizer)
A destructor (also called a finalizer) is a method that is automatically invoked before an object is garbage collected to clean up resources like file handles or database connections.
Example:
class FileHandler
{
~FileHandler()
{
Console.WriteLine("Cleaning up resources...");
}
}
Since .NET manages memory with garbage collection, destructors are rarely needed except for managing unmanaged resources.
26. static
The static keyword indicates that a member (field, method, or property) or an entire class belongs to the type itself, rather than any specific object.
Example:
class MathHelper
{
public static double Pi = 3.14159; // Static field
public static int Square(int x) // Static method
{
return x * x;
}
}
Static members are shared across all instances and do not require object instantiation. A static class cannot be instantiated and can only contain static members.
27. this keyword
The this keyword refers to the current instance of a class or struct. It is used to disambiguate between instance members and method parameters with the same name.
Example:
class Person
{
private string name;
public void SetName(string name)
{
this.name = name; // Refers to the instance field
}
}
It is also used to chain constructors within a class.
28. base keyword
The base keyword is used in a derived class to reference the parent (base) class's members, including constructors, methods, and properties.
Example:
class Animal
{
public void Speak()
{
Console.WriteLine("Animal makes a sound.");
}
}
class Dog : Animal
{
public void Bark()
{
base.Speak(); // Calls the base class method
Console.WriteLine("Dog barks.");
}
}
It is also commonly used in constructor chaining:
class Mammal
{
public Mammal(string type)
{
Console.WriteLine($"Mammal: {type}");
}
}
class Cat : Mammal
{
public Cat() : base("Cat") {} // Calls base constructor
}
29. inheritance
Inheritance is an object-oriented programming (OOP) principle where a class (child) derives from another class (parent) to reuse and extend its functionality.
Example:
class Animal
{
public void Eat()
{
Console.WriteLine("Eating...");
}
}
class Dog : Animal // Inheriting from Animal
{
public void Bark()
{
Console.WriteLine("Barking...");
}
}
A child class can access public and protected members of the parent class. Inheritance promotes code reuse and hierarchical structuring of classes.
30. polymorphism
Polymorphism allows objects to be treated as instances of their base class, enabling method overriding to change behavior in derived classes.
Example:
class Animal
{
public virtual void Speak()
{
Console.WriteLine("Animal makes a sound.");
}
}
class Cat : Animal
{
public override void Speak()
{
Console.WriteLine("Cat meaows.");
}
}
Here, Speak() is overridden in Cat, providing a specialized implementation while maintaining a consistent interface.
Polymorphism enables flexibility and extensibility in applications by allowing derived classes to customize base class behavior.
31. encapsulation
Encapsulation is a fundamental object-oriented programming (OOP) principle that hides data and logic from external code while exposing only what is necessary. This protects internal object states and ensures controlled access to data through methods and properties rather than direct manipulation.
Encapsulation is commonly enforced using access modifiers:
- private (only accessible within the same class)
- protected (accessible within the same class and derived classes)
- public (accessible from anywhere)
- internal (accessible within the same assembly)
Example:
class BankAccount
{
private decimal balance; // Encapsulated field
public decimal Balance
{
get { return balance; } // Controlled access
private set { balance = value; }
}
public void Deposit(decimal amount)
{
if (amount > 0)
Balance += amount;
}
}
Encapsulation improves data integrity, security, and code maintainability.
32. interface
An interface defines a contract that classes must follow by specifying method, property, and event signatures without implementations. Interfaces enable multiple inheritance and promote loose coupling in software design.
Example:
interface IAnimal
{
void Speak(); // Method signature without implementation
}
class Dog : IAnimal
{
public void Speak() { Console.WriteLine("Bark!"); }
}
Interfaces allow objects to be used in a generic way, improving code flexibility and testability.
33. struct
A struct is a lightweight value type used for small, immutable data structures. Unlike classes, structs do not support inheritance and are allocated on the stack, making them more memory-efficient.
Example:
struct Point
{
public int X { get; set; }
public int Y { get; set; }
}
Structs are best for small, immutable, and performance-sensitive data types, like coordinates or colors.