C# this Reference

Description

The this reference refers to the instance itself.

The this reference is valid only within nonstatic members of a class or struct.

Example

Example for this Reference


using System;//from ww  w .  j a  v a2  s . c  om
class Rectangle {
   public int Width;
   public int Height;
   public Rectangle(int w = 5, int h = 6){
     this.Width = w;
     this.Height = h;
   }
}

class Program
{
    static void Main(string[] args)
    {
        Rectangle r = new Rectangle();
        Console.WriteLine(r.Width);
        Console.WriteLine(r.Height);
    }
}

The output:

this and name shading

this can be used to avoid name shading.


using System;//from w w  w . j ava2s  .com
class Rectangle {
   public int Width;
   public int Height;
   public Rectangle(int Width, int Height){
     this.Width = Width;
     this.Height = Height;
   }
}

class Program
{
    static void Main(string[] args)
    {
        Rectangle r = new Rectangle(2,3);
        Console.WriteLine(r.Width);
        Console.WriteLine(r.Height);
    }
}

The output:

this cannot be used in static context.

this calls constructors

The general form using this to call constructors is shown here:


constructor-name(parameter-list1) : this(parameter-list2) {
   // ... body of constructor, which may be empty
}

The following code shows how to use this keyword to call constructors.


using System;  /* w  w  w .ja va2  s. c o m*/
  
class XYCoord {   
  public int x, y;   
   
  public XYCoord() : this(0, 0) { 
    Console.WriteLine("Inside XYCoord()"); 
  }  
 
  public XYCoord(XYCoord obj) : this(obj.x, obj.y) { 
    Console.WriteLine("Inside XYCoord(obj)"); 
  }  
 
  public XYCoord(int i, int j) {  
    Console.WriteLine("Inside XYCoord(int, int)"); 
    x = i; 
    y = j; 
  }     
}     
     
class MainClass {     
  public static void Main() {     
    XYCoord t1 = new XYCoord();   
    XYCoord t2 = new XYCoord(8, 9);   
    XYCoord t3 = new XYCoord(t2);   
   
    Console.WriteLine("t1.x, t1.y: " + t1.x + ", " + t1.y);  
    Console.WriteLine("t2.x, t2.y: " + t2.x + ", " + t2.y);  
    Console.WriteLine("t3.x, t3.y: " + t3.x + ", " + t3.y);  
  }     
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor