Search code examples
c#keywordshorthand

Is there C# shorthand to create a new instance of a containing type?


Say I have a class called Foo, and inside Foo is a static method called GetInstance that returns type Foo. Is there a C# shorthand way for GetInstance create an instance of Foo without having to type "new Foo()"?

In other words, if you call a method that creates an object of the same type that the method belongs to, is there a special C# keyword that creates an instance of the containing type?

Code example:

public class Foo
{
    public static Foo GetInstance()
    {
        return new Foo(); //is there something like new container() or maybe just constructor()
    }
}

Solution

  • No, there is no such keyword in C#.

    The shortest method I can think of that doesn't actually refer to the enclosing type is using reflection:

    return Activator.CreateInstance(MethodBase.GetCurrentMethod().DeclaringType);
    

    But note that:

    • It will be slower than referencing the type directly (whether it affects the performance overall depends on how often it's called)
    • It only works if the type has a constructor with no parameters

    So use at your own risk...