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()
}
}
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:
So use at your own risk...