Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

This is It! Using the This Reference in C#

Let's discuss the basic principles of OOP (Object-Oriented Programming) and how the "this" keyword comes into the picture.

Jan 9, 2020 • 8 Minute Read

Introduction

In order to understand the this keyword in C#, we need to take a journey into the OOP (Object-Oriented Programming) realm. We will discuss the basic principles of OOP and how the this keyword comes into the picture when we are working with classes and their instances.

Object-Oriented Programming

C# fully supports the Object-Oriented Paradigm, including the concepts of encapsulation, inheritance, and polymorphism.

Encapsulation: This term means that a group of related properties, methods, and members are treated as a single unit we refer to as an object.

Inheritance: This term refers to an ability to create a new class based on an existing class.

Polymorphism: This term refers to the idea that you can have multiple classes that are interchangeable, and each class can implement a method or property differently.

The terms class and object, or instance, are sometimes used interchangeably. However, we need to be careful as these terms refer to different things. In fact, classes describe a specific type of object or objects, while objects are usable instances of classes. We call the act of creating an object instantiation.

In everyday language, we could say that classes resemble animals, and objects resemble an actual dog, cat, or whatever type of animal comes to mind. Or, if you are familiar with ancient Greek philosophy, you could say that classes are like ideas, and objects are an embodiment of an idea. For example, there is the concept of love, and there are situations when you love someone.

Let's create a sample class and instantiate it!

      using System;

namespace ThisReference
{
    public class ThisRef
    {
        public class SampleClass {
            public string SampleProperty { get; set; }
            public string SampleMethod(string message)
            {
                return $"This is the message: {message}";
            }
        }
        static void Main(String[] args)
        {
            SampleClass test = new SampleClass();
            test.SampleProperty = "Pluralsight";
            Console.WriteLine($"This is the value of the SampleProperty: {test.SampleProperty}");
            Console.WriteLine($"This is the message from the SampleMethod: {test.SampleMethod("This is cool")}");
            Console.Read();
        }
    }
}
    

The output looks like this.

      This is the value of the SampleProperty: Pluralsight
This is the message from the SampleMethod: This is the message: This is cool
    

This example is important for multiple reasons. It demonstrated the auto-property and how you can implement properties and methods in your classes and call them.

Note how we set the SampleProperty with the test.SampleProperty line, which actually works because we implemented the {get;set;} in the property. We also called the SampleMethod, which returned a string with the specified message. This was a very basic demo, so let's complicate things a bit further.

Let's demonstrate our inheritance.

      using System;

namespace ThisReference
{
    public class ThisRef
    {
        public class A
        {
            public string whatstring = "Default value";
            public void WhatMethod()
            {
                Console.WriteLine($"Coming from class A, what string: {whatstring}!");
            }
        }
        public class B : A
        {
            public void setstring (string newvalue)
            {
                whatstring = newvalue;
            }
        }
        static void Main(String[] args)
        {
            B c = new B();
            Console.WriteLine($"Default value of whatstring: {c.whatstring} coming from class A!");
            c.setstring("New Value");
            Console.WriteLine($"Calling inherited method of WhatMethod: c.setstring() with result of: {c.whatstring}");
            Console.Read();
        }
    }
}
    

The result looks like this.

      Default value of whatstring: Default value coming from class A!
Calling inherited method of WhatMethod: c.setstring() with result of: New Value
    

Note how we inherited the property of whatstring from A base class, along with the function called WhatMethod. We only called the setstring method implemented in the B class to modify the inherited property. Then the output concludes our modifications and shows the very definition of inheritance.

      using System;

namespace ThisReference
{
    public class ThisRef
    {
        public class PolyMomo
        {
            public string PropertyOne = "DefaultOne";
            public string PropertyTwo = "DefaultTwo";

            public void Properties(string one, string two)
            {
                PropertyOne = one;
                PropertyTwo = two;
            }

            public void Properties(string onlyFirst)
            {
                PropertyOne = onlyFirst;
            }
        }
        static void Main(String[] args)
        {
            PolyMomo Demo = new PolyMomo();
            Console.WriteLine($"Property values before change, PropertyOne: {Demo.PropertyOne}, PropertyTwo: {Demo.PropertyTwo}");
            Demo.Properties("first", "second");
            Console.WriteLine($"Both properties were changed PropertyOne: {Demo.PropertyOne}, and PropertyTwo: {Demo.PropertyTwo}");
            PolyMomo DemoTwo = new PolyMomo();
            Console.WriteLine($"Property value before change, PropertyOne: {Demo.PropertyOne}!");
            DemoTwo.Properties("OnlyFirst");
            Console.WriteLine($"Only first property was changed to: {DemoTwo.PropertyOne}");
            Console.Read();
        }
    }
}
    

This gives us the following output:

      Property values before change, PropertyOne: DefaultOne, PropertyTwo: DefaultTwo
Both properties were changed PropertyOne: first, and PropertyTwo: second
Property value before change, PropertyOne: first!
Only first property was changed to: OnlyFirst
    

This demonstration is perfect to prove the polymorphic nature of our class. We have defined the Properties method with two signatures. The first one changes both of the properties we have in our class. The second one is changes only the value of the PropertyOne in our class.

There is a catch, however. If we would like to change only the second property, called PropertyTwo, we are unable to define the following function.

      public void Properties(string onlySecond)
	{
		PropertyTwo = onlySecond;
	}
    

This gives us the error:

CS0121 The call is ambiguous between the following methods or properties: 'ThisRef.PolyMomo.Properties(string)' and 'ThisRef.PolyMomo.Properties(string)' Pluralsight

This means that the same type of parameter signature cannot be present in our class.

The This Reference

The this keyword is used to reference the current instance of a class, or an object itself, if you will. It is also used to differentiate between method parameters and class fields if they both have the same name. If you want to go extremes, you can also use the keyword to call another constructor from a constructor in the same class.

Our demonstration looks like this.

      using System;

namespace ThisReference
{
    public class ThisRef
    {
        public class Thissser
        {
            public string whatever;
            public Thissser(string whatever) {
                this.whatever = whatever;
                Console.WriteLine($"The constructor was called with argument :: {whatever}");
            }
        }
        static void Main(String[] args)
        {
            Thissser Demo = new Thissser("Well this is it!");
            Console.Read();
        }
    }
}
    

This returns the following output.

      The constructor was called with argument :: Well this is it!
    

Conclusion

In this guide, you've learned about the this keyword. I wrapped it in the OOP package as much as possible, going through the necessary fields that allow you to gain better understanding of the function of this keyword. We closed our guide with a demonstration code that shows how you can apply your newly gained knowledge and incorporate it into your applications. I hope this has been informative to you and you found what you were looking for.

Dániel Szabó

Dániel Szabó

Written content author.

More about this author