user3163495
user3163495

Reputation: 3672

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()
    }
}

Upvotes: 0

Views: 276

Answers (1)

D Stanley
D Stanley

Reputation: 152626

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...

Upvotes: 2

Related Questions