HI WELCOME TO SIRIS

C# this

Leave a Comment
In c# programming, this is a keyword that refers to the current instance of the class. There can be 3 main usage of this keyword in C#.
  • It can be used to refer current class instance variable. It is used if field names (instance variables) and parameter names are same, that is why both can be distinguish easily.
  • It can be used to pass current object as a parameter to another method.
  • It can be used to declare indexers.

C# this example

Let's see the example of this keyword in C# that refers to the fields of current class.
  1. using System;  
  2.    public class Employee  
  3.     {  
  4.         public int id;   
  5.         public String name;  
  6.         public float salary;  
  7.         public Employee(int id, String name,float salary)  
  8.         {  
  9.             this.id = id;  
  10.             this.name = name;  
  11.             this.salary = salary;  
  12.         }  
  13.         public void display()  
  14.         {  
  15.             Console.WriteLine(id + " " + name+" "+salary);  
  16.         }  
  17.    }  
  18.    class TestEmployee{  
  19.        public static void Main(string[] args)  
  20.         {  
  21.             Employee e1 = new Employee(101, "Sonoo", 890000f);  
  22.             Employee e2 = new Employee(102, "Mahesh", 490000f);  
  23.             e1.display();  
  24.             e2.display();  
  25.   
  26.         }  
  27.     }  
Output:
101 Sonoo 890000
102 Mahesh 490000
We will learn about other usage of this keyword in next chapters.

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.