It is said that using this reference can save memory. Can anyone please explin how "this" can save memory. Following one is a example program.
using System;
public class CreateStudent
{
public static void Main()
{
Student x = new Student();
x.SetId(951);
x.SetName("Ross");
x.SetGPA(3.5);
Console.WriteLine
("The student named {0} has ID # is {1} and a gpa of {2}", x.GetName(), x.GetId(), x.GetGPA());
Console.ReadLine();
}
}
class Student
{
private int id;
private string lastName;
private double gpa;
public int GetId()
{
return id;
}
public void SetId(int id)
{
this.id = id;
}
public string GetName()
{
return lastName;
}
public void SetName(string lastName)
{
this.lastName = lastName;
}
public double GetGPA()
{
return gpa;
}
public void SetGPA(double gpa)
{
this.gpa = gpa;
}
}
//The student named Ross has ID # is 951 and a gpa of 3.5
Loading
Posted Nov 30, 2011, 4:31 PM
VulpesPosted Nov 30, 2011, 3:27 PM
You've now had to change one or the other of them to something else to avoid the conflict which the 'this' keyword was resolving.
Posted Nov 30, 2011, 3:15 PM
using System;
public class CreateStudent
{
public static void Main()
{
Student x = new Student();
x.SetId(951);
x.SetName("Ross");
x.SetGPA(3.5);
Console.WriteLine
("The student named {0} has ID # is {1} and a gpa of {2}", x.GetName(), x.GetId(), x.GetGPA());
Console.ReadLine();
}
}
class Student
{
private int idNumber;
private string lastName;
private double gradePointAverage;
public int GetId()
{
return idNumber;
}
public void SetId(int id)
{
idNumber = id;
}
public string GetName()
{
return lastName;
}
public void SetName(string name)
{
lastName = name;
}
public double GetGPA()
{
return gradePointAverage;
}
public void SetGPA(double gpa)
{
gradePointAverage = gpa;
}
}
//The student named Ross has ID # is 951 and a gpa of 3.5
VulpesPosted Nov 30, 2011, 2:11 PM
1. To distinguish one of a class's fields from a local variable or parameter of the same name within a method or property of that class.
2. In the case of an instance constructor, to chain to another instance constructor of the same class but with a different signature.
3. To distinguish an extension method from an ordinary static method - the former requires the first parameter to be decorated with 'this' to indicate the type of object the method is extending.
4. To declare indexers.
5. To pass a reference to the current object, as a parameter, to a method.
Posted Nov 30, 2011, 1:58 PM
VulpesPosted Nov 30, 2011, 1:50 PM