Hi,
So I just learnt a new concept in C#.
That is, the set and get methods which allow us to set the value of private fields in our classes and to also retrieve their values.
An example code is shown below.
Since we can set the values using the set method as shown in the code below (i.e. setting the private field _id), I am now starting to wonder, do we actually need constructors at all since the set method serves the same purpose?
So I just learnt a new concept in C#.
That is, the set and get methods which allow us to set the value of private fields in our classes and to also retrieve their values.
An example code is shown below.
Since we can set the values using the set method as shown in the code below (i.e. setting the private field _id), I am now starting to wonder, do we actually need constructors at all since the set method serves the same purpose?
C#:
using System;
namespace ConsoleApp33
{
class Student
{
private int _id;
public int Id
{
set
{
if(value <= 0)
{
throw new Exception("Id cannot be negative");
}
this._id = value;
}
get
{
return this._id;
}
}
}
class Program
{
static void Main(string[] args)
{
Student s = new Student();
s.Id = 101;
Console.WriteLine(s.Id);
}
}
}