4

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());
    }
}
Steve
  • 9,335
  • 10
  • 49
  • 81
Zvezda Bre
  • 61
  • 4

3 Answers3

3

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

Community
  • 1
  • 1
Kamil Budziewski
  • 22,699
  • 14
  • 85
  • 105
3

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);
}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
1

Try this

class Student
{
    private int _ID;

    public int ID
    {
        get{ return _ID;}

        set {
            if (value <= 0)
                throw new Exception("It is not a Valid ID");
            _ID = value;
           }

    }


}

class Program
{
    public static void Main()
    {
        Student C1 = new Student();
        C1.ID=101;
        Console.WriteLine("Student ID = {0}", C1.ID);
    }
}
MNF
  • 687
  • 9
  • 13