Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"this" operator not working

Tags:

c#

this

set

get

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());
    }
}
like image 859
Zvezda Bre Avatar asked Mar 13 '23 17:03

Zvezda Bre


2 Answers

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

like image 157
Kamil Budziewski Avatar answered Mar 24 '23 00:03

Kamil Budziewski


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);
}
like image 44
Dmitry Bychenko Avatar answered Mar 24 '23 01:03

Dmitry Bychenko