Methods
A method is a member function in a class.
Access modifier are used to control access.
Regular Methods
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public void PrintDetails()
{
if (ValidateData())
{
Console.WriteLine("ID: {0}, Name: {1}", Id, Name);
}
else
{
Console.WriteLine("ERROR");
}
}
private bool ValidateData()
{
if (Id <= 0 || string.IsNullOrEmpty(Name))
{
return false;
}
else
{
return true;
}
}
}Constructors
A constructor is a special type of a member method.
The method identifier (name) must be identical to the class name.
A constructor cannot have a return type, and can contain zero or more parameters.
The constructor with no parameters is called the default constructor, and is called at the time of object creation.
Typically used for initializing member variables of a class instance, and to perform other important work that must be done up front.
A class may contain more than one constructor.
Below is a meaningful example of a class and usage of constructors.
Last updated