フッターコンテンツにスキップ
.NETヘルプ

C# This (開発者向けの仕組み)

There's a particular keyword in C# that holds special importance, and that is the this keyword. This keyword refers to the current class instance where it's used. It can be used to distinguish between class-level variables and method parameters that share the same name, among other things. For instance, if you have an instance variable and a method parameter with the same name, this can be a lifesaver!

The Basics of this Keyword

In a public class, like Employee for example, you may have public instance variables such as id or name. If you want to assign values to these instance variables inside a method, you might stumble upon a common problem: What if the method parameters have the same name as the instance variables?

Here's a solution: Use the this keyword in C# documentation! In the following example of a method inside the public class Employee, the this keyword is used to distinguish between the instance variables and the method parameters that share the same names.

public class Employee
{
    private int id;
    private string name;

    public void Display(int id, string name)
    {
        // Use `this.id` to refer to the instance variable, 
        // and `id` for the method parameter.
        this.id = id;
        this.name = name;
    }
}
public class Employee
{
    private int id;
    private string name;

    public void Display(int id, string name)
    {
        // Use `this.id` to refer to the instance variable, 
        // and `id` for the method parameter.
        this.id = id;
        this.name = name;
    }
}
Public Class Employee
	Private id As Integer
	Private name As String

	Public Sub Display(ByVal id As Integer, ByVal name As String)
		' Use `this.id` to refer to the instance variable, 
		' and `id` for the method parameter.
		Me.id = id
		Me.name = name
	End Sub
End Class
$vbLabelText   $csharpLabel

In this case, this.id refers to the instance variable, and id is the method parameter.

this Keyword in Constructor Overloading

By leveraging the this keyword, constructor overloading becomes a powerful technique within the same class. When a class, such as a Student class, has multiple constructors with varying parameters, the this keyword allows one constructor to call another, eliminating the need for redundant code.

Consider the following example where this is used in a parameterized constructor:

public class Student
{
    private string name;
    private int id;

    public Student() : this("Default", 0)
    {
        // Default constructor delegates to the parameterized constructor
        // with "Default" as the name and 0 as the id.
    }

    public Student(string name, int id)
    {
        // Assign the parameters to the instance variables
        this.name = name;
        this.id = id;
    }
}
public class Student
{
    private string name;
    private int id;

    public Student() : this("Default", 0)
    {
        // Default constructor delegates to the parameterized constructor
        // with "Default" as the name and 0 as the id.
    }

    public Student(string name, int id)
    {
        // Assign the parameters to the instance variables
        this.name = name;
        this.id = id;
    }
}
Public Class Student
	Private name As String
	Private id As Integer

	Public Sub New()
		Me.New("Default", 0)
		' Default constructor delegates to the parameterized constructor
		' with "Default" as the name and 0 as the id.
	End Sub

	Public Sub New(ByVal name As String, ByVal id As Integer)
		' Assign the parameters to the instance variables
		Me.name = name
		Me.id = id
	End Sub
End Class
$vbLabelText   $csharpLabel

In the parameter-less constructor, this("Default", 0) calls the parameterized constructor, setting Default as the name and 0 as the ID.

Exploring this in Extension Methods

Extension methods in C# provide a way to add methods to existing types without modifying the original type. Here's where the this keyword does something magical. It's used in the parameter list of the extension method to refer to the type being extended.

Consider the following example of an extension method:

public static class StringExtensions
{
    // This extension method can be called on any string instance
    public static bool IsNullOrEmpty(this string str)
    {
        return string.IsNullOrEmpty(str);
    }
}
public static class StringExtensions
{
    // This extension method can be called on any string instance
    public static bool IsNullOrEmpty(this string str)
    {
        return string.IsNullOrEmpty(str);
    }
}
Public Module StringExtensions
	' This extension method can be called on any string instance
	<System.Runtime.CompilerServices.Extension> _
	Public Function IsNullOrEmpty(ByVal str As String) As Boolean
		Return String.IsNullOrEmpty(str)
	End Function
End Module
$vbLabelText   $csharpLabel

Here, this string str tells C# that this is an extension method for the string type. Now you can use this method on any string object, like if(myString.IsNullOrEmpty()).

this in Indexers

The this keyword can also be used in defining indexers. An indexer allows instances of a class to be indexed just like arrays. This helps you access data within objects using index-like notation. In an indexer, this is followed by an array index, which is usually int index.

Here's a basic example of an indexer:

public class Test
{
    private int[] array = new int[100];

    // Define an indexer for the class
    public int this[int index]
    {
        get { return array[index]; }
        set { array[index] = value; }
    }
}
public class Test
{
    private int[] array = new int[100];

    // Define an indexer for the class
    public int this[int index]
    {
        get { return array[index]; }
        set { array[index] = value; }
    }
}
Public Class Test
	Private array(99) As Integer

	' Define an indexer for the class
	Default Public Property Item(ByVal index As Integer) As Integer
		Get
			Return array(index)
		End Get
		Set(ByVal value As Integer)
			array(index) = value
		End Set
	End Property
End Class
$vbLabelText   $csharpLabel

In this class Test, the this keyword defines an indexer that can be used to get or set values in the array instance field.

this and Static Members

One thing to note about this is that it cannot be used to reference static members or methods. This is because this refers to the current instance, and static members belong to the class itself, not an instance of the class.

public class Program
{
    public static void Main(string[] args)
    {
        // Can't use `this` here, because 'Main' is a static method.
    }
}
public class Program
{
    public static void Main(string[] args)
    {
        // Can't use `this` here, because 'Main' is a static method.
    }
}
Public Class Program
	Public Shared Sub Main(ByVal args() As String)
		' Can't use `this` here, because 'Main' is a static method.
	End Sub
End Class
$vbLabelText   $csharpLabel

So, remember, this is for instances, not for class-level or static members!

this Keyword and Properties

Just like instance variables and method parameters, the this keyword can also be used with properties. In C#, a property is a member that provides a flexible mechanism for reading, writing, or computing the value of a private field. Properties can be used as if they are public data members, but they are actually special methods called accessors.

Let's look at a simple example using this in a property:

public class Employee
{
    private string name;

    public string Name
    {
        get { return this.name; }
        set { this.name = value; } // Use `this` to refer to the instance variable
    }
}
public class Employee
{
    private string name;

    public string Name
    {
        get { return this.name; }
        set { this.name = value; } // Use `this` to refer to the instance variable
    }
}
Public Class Employee
'INSTANT VB NOTE: The field name was renamed since Visual Basic does not allow fields to have the same name as other class members:
	Private name_Conflict As String

	Public Property Name() As String
		Get
			Return Me.name_Conflict
		End Get
		Set(ByVal value As String)
			Me.name_Conflict = value
		End Set ' Use `this` to refer to the instance variable
	End Property
End Class
$vbLabelText   $csharpLabel

In the above class, the this keyword is used to refer to the private string name in the get and set accessors of the Name property.

Exploring this and Delegates

Another place where this shows up is in delegates. A delegate in C# is similar to a function pointer in C or C++. It's a reference-type variable that holds the reference to a method. Delegate methods, just like extension methods, can use this to access the current instance.

Here's an example of a delegate using this:

public delegate void DisplayDelegate();

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }

    public void Display()
    {
        // `this.DisplayDetails` refers to the method instance of the current object.
        DisplayDelegate displayDelegate = new DisplayDelegate(this.DisplayDetails);
        displayDelegate();
    }

    private void DisplayDetails()
    {
        Console.WriteLine("ID: " + Id + ", Name: " + Name);
    }
}
public delegate void DisplayDelegate();

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }

    public void Display()
    {
        // `this.DisplayDetails` refers to the method instance of the current object.
        DisplayDelegate displayDelegate = new DisplayDelegate(this.DisplayDetails);
        displayDelegate();
    }

    private void DisplayDetails()
    {
        Console.WriteLine("ID: " + Id + ", Name: " + Name);
    }
}
Public Delegate Sub DisplayDelegate()

Public Class Student
	Public Property Id() As Integer
	Public Property Name() As String

	Public Sub Display()
		' `this.DisplayDetails` refers to the method instance of the current object.
		Dim displayDelegate As New DisplayDelegate(AddressOf Me.DisplayDetails)
		displayDelegate()
	End Sub

	Private Sub DisplayDetails()
		Console.WriteLine("ID: " & Id & ", Name: " & Name)
	End Sub
End Class
$vbLabelText   $csharpLabel

In the student class, this.DisplayDetails creates a new instance of the delegate that refers to the DisplayDetails method of the current object.

Implementing this Keyword with IronPDF

Let's delve into an example where you might use the this keyword in conjunction with IronPDF, a powerful .NET library for editing and creating PDF files using HTML.

Consider a class named PDFHandler that uses the IronPDF library to perform various operations on PDF files:

using IronPdf;

public class PDFHandler
{
    private string path;

    public PDFHandler(string path)
    {
        this.path = path;
    }

    public void GeneratePDF(string content)
    {
        // Creating a renderer to convert HTML content to PDF
        var Renderer = new IronPdf.ChromePdfRenderer();
        var PDF = Renderer.RenderHtmlAsPdf(content);

        // Save the generated PDF to the path specified by the current instance
        PDF.SaveAs(this.path);
    }
}
using IronPdf;

public class PDFHandler
{
    private string path;

    public PDFHandler(string path)
    {
        this.path = path;
    }

    public void GeneratePDF(string content)
    {
        // Creating a renderer to convert HTML content to PDF
        var Renderer = new IronPdf.ChromePdfRenderer();
        var PDF = Renderer.RenderHtmlAsPdf(content);

        // Save the generated PDF to the path specified by the current instance
        PDF.SaveAs(this.path);
    }
}
Imports IronPdf

Public Class PDFHandler
	Private path As String

	Public Sub New(ByVal path As String)
		Me.path = path
	End Sub

	Public Sub GeneratePDF(ByVal content As String)
		' Creating a renderer to convert HTML content to PDF
		Dim Renderer = New IronPdf.ChromePdfRenderer()
		Dim PDF = Renderer.RenderHtmlAsPdf(content)

		' Save the generated PDF to the path specified by the current instance
		PDF.SaveAs(Me.path)
	End Sub
End Class
$vbLabelText   $csharpLabel

In this PDFHandler class, the this keyword is used to refer to the path field of the current instance. This field is used to save the generated PDF to the specified path.

When we create a new instance of PDFHandler and call the GeneratePDF method, the this keyword allows us to utilize the path specified during object creation:

class Program
{
    static void Main(string[] args)
    {
        // Initialize PDFHandler with a specified file path
        PDFHandler pdfHandler = new PDFHandler("C:\\ThisKeyword.pdf");
        pdfHandler.GeneratePDF("Hello World!");
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Initialize PDFHandler with a specified file path
        PDFHandler pdfHandler = new PDFHandler("C:\\ThisKeyword.pdf");
        pdfHandler.GeneratePDF("Hello World!");
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Initialize PDFHandler with a specified file path
		Dim pdfHandler As New PDFHandler("C:\ThisKeyword.pdf")
		pdfHandler.GeneratePDF("Hello World!")
	End Sub
End Class
$vbLabelText   $csharpLabel

Here, this makes the code more readable and understandable, especially when dealing with libraries like IronPDF.

C# This (How It Works For Developers) Figure 1

結論

By now, you should have a good understanding of the this keyword in C#, including its wide-ranging uses, from simple instance variables to complex contexts such as constructors, extension methods, properties, delegates, anonymous methods, and even when using popular libraries like IronPDF.

Remember, IronPDF offers a free trial of IronPDF, so you can put to the test everything you've learned today. If you decide to continue with it, licenses start from just \$liteLicense. IronPDF can be a worthy addition to your C# development toolkit, simplifying the task of handling PDF files in your applications.

よくある質問

C#で「this」キーワードがクラス変数とメソッドパラメータをどのように区別できるか?

C#の「this」キーワードは現在のクラスインスタンスを参照するために使用され、同じ名前を共有するクラスレベルの変数とメソッドパラメータを区別できます。これは特にメソッド内の命名の競合を避けるのに役立ちます。

コンストラクタのオーバーロードにおける「this」の重要性は何か?

コンストラクタのオーバーロードでは、『this』を使用して同じクラス内の他のコンストラクタを呼び出せます。これにより、既存のコンストラクタロジックを再利用し、冗長なコードを減らし、一貫性と保守性を確保できます。

C#で拡張メソッドの使用を『this』がどのように促進するか?

拡張メソッドのメソッドパラメータリストでは、『this』キーワードを使用して拡張される型を示します。これにより、開発者は既存の型のソースコードを変更することなく新しいメソッドを追加でき、機能をシームレスに拡張できます。

インデクサーでの『this』の使用方法は?

C#では、『this』はインデクサーとともに使用され、クラスインスタンスを配列のような表記法でアクセスできるプロパティを定義します。これにより、オブジェクト内のデータアクセスの読みやすさと使いやすさが向上します。

なぜ静的メンバーにはC#で「this」を使用できないのか?

『this』キーワードはクラスのインスタンスメンバーを参照しますが、静的メンバーは特定のインスタンスではなく、クラス自体に属します。そのため、「this」は静的メンバーまたはメソッドを参照するためには使用できません。

C#クラスで「this」キーワードがプロパティアクセスをどのように強化するか?

プロパティのgetおよびsetアクセサ内で、『this』キーワードを使用して、現在のクラスインスタンスのプライベートフィールドを参照できます。これにより、操作がクラス自身のフィールドで行われることを明示的に示し、コードの明確さが向上します。

委任のコンテキストでの『this』の役割は何か?

委託のコンテキストでは、『this』により、委任が現在のオブジェクトのメソッドインスタンスを参照できるようになります。これは、イベントハンドリングやコールバックにおいて柔軟性を提供するために、委任を通じてインスタンスメソッドを呼び出すのに重要です。

IronPDFライブラリを使用する際に、「this」がコードの読みやすさをどのように向上させるか?

IronPDFライブラリを使用する場合、「this」はファイルパスなどのインスタンス変数を明確に示すことで、コードをより読みやすくできます。これは、PDFファイルの生成や保存などの操作を行う際に、コードの明確さと保守性を高めるのに特に有用です。

Curtis Chau
テクニカルライター

Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。

開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。