"this" Keyword in c#
"This" keyword is used to refer to the current object of the class. It is used to resolve conflicts between variables having the same names and to pass the current object as a parameter. You cannot use this keyword with static variables and methods.
Example 1:
class person
{
private string name;
public person(string name)
{
//use the "this" keyword to set the local variable
this.name = name;
}
public void introduceyourself()
{
Console.WriteLine("Hello, My name is " + this.name);
Console.ReadKey();
}
}
class Program
{
static void Main(string[] args)
{
person personobj = new person("TEXVN");
personobj.introduceyourself();
}
}
Output:-
Hello, My name is TEXVN
Example 2:
class myclass
{
private int num;
public myclass(int num)
{
//Use the "this" keyword to disambiguate between the parameter
and the class feild
this.num = num;
}
public void displaynum()
{
//Use the "This" keyword to access the class number
Console.WriteLine("Number Value: " + this.num);
Console.ReadKey();
}
}
class program
{
static void Main(string[] args)
{
myclass myclassobj = new myclass(60);
myclassobj.displaynum();
}
}
Output:-
Number Value: 60
Web Developer | App Developer | Freelancer | Blogger
More From:
Zia
Multithreading and Asynchronous Programming
C#Â applications often have to execute multiple tasks concurrently. For example, a C# ...
Rakuten Advertising: A Complete Guide
Rakuten Advertising is a performance advertising community that connects advertisers with publishers ...
Guide SEO-friendly Content and Importance...
Search engines are essentially free advertising platforms to promote SEO-friendly content. Writing SEO-friendly ...
What is AJAX and Working...
AJAX Asynchronous JavaScript and XML is not a new technology but a new approach to ...
Recomended
The Null-Coalescing (??) Operator in...
C# provides nullable types to identify and handle value-type fields with null ...
Properties in C# { get...
Access modifiers such as public, private, protected, and internal control the accessibility ...
Conversation
Your input fuels progress! Share your tips or experiences on prioritizing mental wellness at work. Let's inspire change together!
Join the discussion and share your insights now!
Comments 0