get and set are accessors used in properties to encapsulate fields and control how values are accessed and modified.
class Person
{
private string name; // Private field
public string Name // Property with get and set
{
get { return name; } // Getter
set { name = value; } // Setter
}
}
Property with Validation
csharp
class Person
{
private int age;
public int Age
{
get { return age; }
set
{
if (value >= 0) age = value; // Validation
else throw new ArgumentException("Age cannot be negative.");
}
}
}
A method in C# is a block of code that performs a specific task. It helps in code reusability and modular programming. Methods are defined inside a class and can be called multiple times.
class Program
{
static void SayHello()
{
Console.WriteLine("Hello, World!");
}
static void Main()
{
SayHello(); // Calling the method
}
}
A constructor is a special method in C# that is automatically called when an object of a class is created. It is used to initialize an object’s properties and set up any required resources.
class Person
{
public string Name;
// Default constructor
public Person()
{
Name = "Unknown";
Console.WriteLine("Constructor called!");
}
}
class Program
{
static void Main()
{
Person p = new Person(); // Constructor is called automatically
Console.WriteLine(p.Name);
}
}
Top comments (0)