Is it clean to create an instance of a class inside a static method of that class?

Viewed 135

I have a non-static class and a static method inside it. No doubts so far. but I create an instance of the same class in the static method. I am not sure, whether it will create a circular reference. I ran it in debug mode to see any unexpected behavior, but couldn't. However, I want to confirm this. Is it ok to create an instance of a class inside a static method in the same class? Is it a bad habit?

public class DownloadHelper
{
    //fields, properties

    public DownloadHelper()
    {
        // some code
    }

    public async Task<bool> HttpCalls()
    {
        await Task.Delay(1000);
        return true;
    }

    public static async void GetPreparedInAdvance()
    {
        var helper = new DownloadHelper();
        var success = await helper.HttpCalls();
        // some more codes
    }
}

// Is it ok to call like this?
DownloadHelper.GetPreparedInAdvance();

// little later,
DownloadHelper.GetPreparedInAdvance();
1 Answers

There is no problem and what this code does is conventional.

Using static methods to create an object instance:

Here it is a variation of what I call a static run method pattern*:

  • It creates an object instance of the class on each call, or can be unique if singleton,
  • It executes this instance : display a form, or download a file from the web, and so on,
  • And it returns a result, or not : of the dialog box or of the file, and so on.

With such a pattern, constructors are generally private to ensure consistency.


*I have not yet studied the standard design patterns

Related