The "this" operator does not work

Every time I use this._Something, it is this.light blue and has a green underline. And I can not get the value 101 after F5. Instead, I get a value of 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());
    }
}
+4
source share
3 answers

You assign _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 call thisis lightblue because VS tells you that you don't need to use it here. You do not have a local variable with the same name. Read more about this here

By the way, you should read about properties with support fields, for example here

+3
source

get set ; Java #:

 class Student {
   private int _ID; 

   public int ID {
     get {
       return _ID;
     }
     set {
       // input validation:
       // be exact, do not throw Exception but ArgumentOutOfRangeException:
       // it argument that wrong and it wrong because it 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);
}
+3

try it

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);
    }
}
+1
source

All Articles