Every time I use this._Something
, my this.
is light blue and it has green underline. And I cant get value 101 after F5. Instead, I get value 0. Any help ?
class Student
{
private int _ID;
public void SetID(int Id)
{
if (Id <= 0)
{
throw new Exception("It is not a Valid ID");
this._ID = Id;
}
}
public int GetID()
{
return this._ID;
}
}
class Program
{
public static void Main()
{
Student C1 = new Student();
C1.SetID(101);
Console.WriteLine("Student ID = {0}", C1.GetID());
}
}
You are assigning _ID only if (Id <= 0), change your code to:
public void SetID(int Id)
{
if (Id <= 0)
{
throw new Exception("It is not a Valid ID");
}
_ID = Id;
}
Your this
call is lightblue, because VS is telling you that you don't need to use it here. You don't have local variable with same name. Read more about this
here
BTW you should read about properties with backing fields, for example here
I suggest redesigning both get
and set
methods into single property; you have no need to mimic Java in C#:
class Student {
private int _ID;
public int ID {
get {
return _ID;
}
set {
// input validation:
// be exact, do not throw Exception but ArgumentOutOfRangeException:
// it's argument that's wrong and it's wrong because it's out of range
if (value <= 0)
throw new ArgumentOutOfRangeException("value", "Id must be positive");
_ID = value;
}
}
}
...
public static void Main()
{
Student C1 = new Student();
C1.ID = 101;
Console.WriteLine("Student ID = {0}", C1.ID);
}
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