CAN “THIS” BE USED WITHIN A STATIC METHOD IN C#

Manoj Bhatt

Total Post:154

Points:1086
Posted by  Manoj Bhatt
C#  .NET 
C#
 1469  View(s)
Ratings:
Rate this:
Hi All..
I want to know , can i used 'this' keyword inside a static method.

Thank you.
  1. Shiva Shukla

    Post:13

    Points:91
    Re: Can “this” be used within a static method in c#

    We can't use this in static method because keyword 'this' returns a reference to the current instance of the class containing it. Static methods (or any static member) do not belong to a particular instance.

    The "this" keyword is a special type of reference variable that is implicitly defined within each constructor and non-static method as a first parameter of the type class in which it is defined.

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Text;

    namespace
    this_example

    {

        class Program

        {

            public class Demo

            {

                int age;

                string name;

     

                public Demo(int age, string name)

                {

                    age = age;

                    name = name; 

                }

     

                public void Show()

                {

                    Console.WriteLine("Your age is :" + age.ToString());

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

                }

            }

     

            static void Main(string[] args)

            {

                int _age;

                string _name;

     

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

                _age=Int32.Parse(Console.ReadLine());

     

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

                _name=Console.ReadLine();

     

                Demo obj = new Demo(_age, _name);

     

                obj.Show();

                Console.ReadLine();

             }

        }

    }
     

    Output of the above program will be:
     

  1. Todd Jenny

    Post:2

    Points:14
    Re: Can “this” be used within a static method in c#

    Post is removed by the Admin.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!