Using Getter and Setter:
using System;
public class Student
{
private int _id;
private string _name;
private int _passmark = 35;
public int GetPassMark()
{
return this._passmark;
}
public void SetName (string Name)
{
if (string.IsNullOrEmpty(Name))
{
throw new Exception("Name cannot be null or empty");
}
this._name = Name;
}
public string GetName()
{
return string.IsNullOrEmpty(this._name) ? "No Name" : this._name;
//if (string.IsNullOrEmpty(this._name))
//{
// return "No Name";
//}
//else
//{
// return this._name;
//}
}
public void SetId(int Id)
{
if (Id <= 0)
{
throw new Exception("Student ID cannot be a negative");
}
this._id = Id;
}
public int GetId()
{
return this._id;
}
}
public class Program
{
public static void Main()
{
Student C1 = new Student();
C1.SetId(403130);
C1.SetName("Charlie");
Console.WriteLine("Student ID = {0}", C1.GetId());
Console.WriteLine("Student Name = {0}", C1.GetName());
Console.WriteLine("Student PassMark = {0}", C1.GetPassMark());
}
}
ID number cannot be negative.
Name cannot be empty
Set passmark to read only...
using "private" and getter and setter to impose these restrictions mentioned above.
Using C# properties:
using System;
public class Student
{
private int _id;
private string _name;
private int _passmark = 35;
public int PassMark
{
get
{
return this._passmark; //read only
}
}
public string Name
{
set
{
if (string.IsNullOrEmpty(value))
{
throw new Exception("Name cannot be null or empty");
}
this._name = value;
}
get
{
return string.IsNullOrEmpty(this._name) ? "No Name" : this._name;
}
}
public int Id
{
set
{
if (value <= 0)
{
throw new Exception("Student ID cannot be a negative");
}
this._id = value;
}
get
{
return this._id;
}
}
}
public class Program
{
public static void Main()
{
Student C1 = new Student();
C1.Id = 403130;
C1.Name = "Charlie";
Console.WriteLine("Student ID = {0}", C1.Id);
Console.WriteLine("Student Name = {0}", C1.Name);
Console.WriteLine("Student PassMark = {0}", C1.PassMark);
}
}
this is exactly the same code compared to the one above, but this time we are using C# properties.
Bonus
Auto Implemented Properties:
If there is no additional logic in the property accessors, then we can make use of Auto Implemented Properties.
Normally, we have to write
using System;
public class Student
{
private string _city;
public string City
{
get
{
return this._city;
}
set
{
this._city = value;
}
}
}
Using Auto Implemented Properties, we only need to write
using System;
public class Student
{
public string City {get;set;}
}
When you use auto implemented properties, the compiler creates a private, anonymous field that can only be accessed through the property's get and set methods.