this keyword in C#

In this article I will explain this keyword in C#.
  • 2559

Introduction

The this keyword in c#  refers to the current instance of the class. It can be used to access members from within constructors, instance methods, and instance accessors. Static constructors and member methods do not have a this pointer because they are not instantiated.

Example

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace this_example

{

    public class Demo

    {

            string firstname;

            string secondname;

            public Demo(string firstname, string secondname)

            {

                firstname = firstname;

               

                secondname = secondname;

            }

           public void Show()

            {

                Console.WriteLine("Your firstname is :" + firstname);

                Console.WriteLine("Your secondname is : " + secondname);

            }

    }

    class abc

    {

        static void Main(string[] args)

        {

            string _firstname;

            string _secondname;

            Console.WriteLine("Enter your firstname : ");

            _firstname = Console.ReadLine();

            Console.WriteLine("Enter your secondname : ");

            _secondname = Console.ReadLine();

            Demo obj = new Demo(_firstname, _secondname);

            obj.Show();

            Console.Read();

        }

    }

        } 

Output of the above program will be

Clipboard153.jpg

In this example you are not getting any value. Because in the program the local data members firstname , secondname have precedence over instance members.

Using the this keyword

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace this_example

{

    public class Demo

    {

            string firstname;

            string secondname;

            public Demo(string firstname, string secondname)

            {

                this.firstname = firstname;

               

                this.secondname = secondname;

            }

             public void Show()

            {

                Console.WriteLine("Your firstname is :" + firstname);

                Console.WriteLine("Your secondname is : " + secondname);

            }

    }

    class abc

    {

        static void Main(string[] args)

        {

            string _firstname;

            string _secondname;

            Console.WriteLine("Enter your firstname : ");

            _firstname = Console.ReadLine();

            Console.WriteLine("Enter your secondname : ");

            _secondname = Console.ReadLine();

            Demo obj = new Demo(_firstname, _secondname);

            obj.Show();

            Console.Read();

        }

    }

        }

 

The output of the program


Clipboard154.jpg

 

© 2020 DotNetHeaven. All rights reserved.