Use of this reference in C#


C# is advance language that have feature of c,c++ and java .this reference is one of them. this reference is used to refer to current object of the program and not used by a static member function.in this code we will see how to use this in C#.

use of this reference inC#


C# has many feature of C++ and java.this reference keyword is one of them
The thisis used to current object of the program and not used by a static member function.this keyword is used in C# for access the value of an object within constructor and methods. this method is also used to pass a current object as a parameter to other method using following syntax:
 
method_name(this)

Lets see complete program that show you power of this Reference in C#

using System;
public class Person
public string name;
public string dup1;
public int age = 50;
//constructor
public Person(string name,string dup1)
{
//using this reference
this.name=name;
this.dup1=dup1;
}
public void List()
{
Console.WriteLine("Name:{0}",name);
Console.WriteLine("dup1:{0}",dup1);
Console.WriteLine("Age:{0:C}",Remain_age.Age_cal(this));
}
}

public class Remain_age
{
public static int Age_cal(Person P)
{
return(60-(P.age));
}
}

public class MainClass
{
public static void Main()
{
//new object
Person p1=new Person("preet","sold");
//display
p1.List();
}
}

OUTPUT OF THIS CODE IS:
Name:preet
dup1:sold
Age: $10.00
Press any key to continuee...


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: