i was wondering if there is a way to restrict a value in construction. Here is my code :
class Student : Human
{
private double Grade;
public Student(string FirstName, string LastName, double Grade)
: base(FirstName, LastName)
{
this.FirstName = FirstName;
this.LastName = LastName;
this.Grade = Grade;
}
}
and when i make a new Student i want to restrict the Grade between >= 2.00 and <= 6.00 , like compile error or excepion on runtime. Is there a way ? (Don't worry about other fields FirstName, and LastName)
Rules to be rememberedA constructor does not have return type. The name of the constructor is same as the name of the class. A constructor cannot be abstract, final, static and Synchronized. You can use the access specifiers public, protected & private with constructors.
The following restrictions apply to constructors and destructors: Constructors and destructors do not have return types nor can they return values. References and pointers cannot be used on constructors and destructors because their addresses cannot be taken. Constructors cannot be declared with the keyword virtual .
Explanation: The constructor cannot have a return type. It should create and return new objects. Hence it would give a compilation error.
In Java, constructors can be divided into 3 types: No-Arg Constructor. Parameterized Constructor. Default Constructor.
You can check it and throw an exception at runtime, like this:
if (grade < 2.00 || grade > 6.00)
throw new ArgumentOutOfRangeException("grade");
Always put such conditions at the start of the method or constructor. I even put them in their own #region
(but that's my personal preference):
public Student(string firstName, string lastName, double grade)
: base(firstName, lastName)
{
#region Contract
if (grade < 2.00 || grade > 6.00)
throw new ArgumentOutOfRangeException("grade");
#endregion
this.FirstName = firstName;
this.LastName = lastName;
this.Grade = grade;
}
However, there is a way to get compile-time warnings for such things using Code Contracts. You can download Code Contracts on MSDN and there you can also find the documentation. It only integrates with non-Express versions of Visual Studio and is written by Microsoft. It will check whether method calls are likely to adhere to the contract you specify. Your code would then become:
using System.Diagnotistics.Contracts;
public Student(string firstName, string lastName, double grade)
: base(firstName, lastName)
{
#region Contract
Contract.Requires<ArgumentOutOfRangeException>(grade >= 2.00);
Contract.Requires<ArgumentOutOfRangeException>(grade <= 6.00);
#endregion
this.FirstName = firstName;
this.LastName = lastName;
this.Grade = grade;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With