Reputation: 9664
In msdn article:
Within an instance constructor or instance function member of a class, this is classified as a value. Thus, while this can be used to refer to the instance for which the function member was invoked, it is not possible to assign to this in a function member of a class. Within an instance constructor of a struct, this corresponds to an out parameter of the struct type, and within an instance function member of a struct, this corresponds to a ref parameter of the struct type. In both cases, this is classified as a variable, and it is possible to modify the entire struct for which the function member was invoked by assigning to this or by passing this as a ref or out parameter.
Can you provide me an example for struct and class that shows this.
Upvotes: 0
Views: 84
Reputation: 18747
In a class, the this
keyword refers to the current instance of a class, or the instance that a particular method was invoked on.
You can also use the this
keyword in a struct and it will refer to the current instance of the struct.
Usage in Struct:
In the example below, the this
keyword is used to refer to the fields of the current instance of the struct, to distinguish them from the input parameters that have the same name.
public struct BoxSize
{
public double x;
public double y;
public double z;
public bool HasBiggerVolume(double x, double y, double z)
{
if ((this.x * this.y * this.z) > (x * y * z))
return true;
else
return false;
}
}
Usage in Class:
class student
{
int id;
String name;
student(int id,String name)
{
id = id;
name = name;
}
void display()
{
Console.WriteLine(id+" "+name);
}
public static void main()
{
student s1 = new student(1,"NameA");
student s2 = new student(2,"NameB");
s1.display();
s2.display();
}
}
Output will be:
0 null
0 null
Solution for the problem:
class Student
{
int id;
String name;
student(int id,String name)
{
this.id = id;
this.name = name;
}
void display()
{
Console.WriteLine(id+" "+name);
}
public static void main()
{
Student s1 = new Student(1,"NameA");
Student s2 = new Student(2,"NameB");
s1.display();
s2.display();
}
}
Output will be:
1 NameA
2 NameB
FYI, here is given the 6 usage of this
keyword.
this
keyword can be used to refer current class instance variable.
this()
can be used to invoke current class constructor.
this
keyword can be used to invoke current class method (implicitly)
this
can be passed as an argument in the method call.
this
can be passed as argument in the constructor call.
this
keyword can also be used to return the current class instance.
Upvotes: 4