Search code examples
c#oop

use of creating class object from same the same class method in c#


I have seen some of C# projects to get idea of C# coding. So, I found object creation of class from the function belong to same class. Please explain me the reason and what exactly it will do. Following is sample code.

 class MainClass
{
    void TestChild()
    {
        //some code
    }
    void TestMethod()
    {
        MainClass object1 = new MainClass();
        object1.TestChild();
    }
}

Is it makes any difference by calling directly TestChild from TestMethod.


Solution

  • To me, there is not much difference between this code and yours :

     class MainClass
    {
        void TestChild()
        {
            //some code
        }
        void TestMethod()
        {
            TestChild();
        }
    }
    

    Unless the programmer wants to set up something in the constructor.

    I am not sure why in comment section some people said your code cannot compile. It compiles well. (I have done that too last year without even noticing what I did).

    The reason why declaring a new object to itself within TestMethod, I believe, is to make sure TestMethod uses the right object to execute TestChild method in case of constructor overload.