C# – Call class method while instantiating

c

I don't know how to describe it better so the title might be a bit confusing.

I would like to know if it is possible to instantiate a class by using ... = new MyClass() and to call non static methods of this class instantly while instantiating?

For example something like that:

return new MyClass().SetName("some name");

I guess I have seen something similar like this before but I can't find it.
It is a bit annoying to do something like…

MyClass myclass = new MyClass();
myclass.SetName("some name");
return myclass;

Is there a way to shorten it or to do it like my first example?
(Please do not suggest me to use a property instead of SetName(string) – it is just an example)

Thanks in advance!

Best Answer

Well, if you did have a property, you could use an object initializer:

return new MyClass { Name = "some name" };

If you really, really have to use a method, then the only option is to make the method return the instance again:

public Foo SomeMethod()
{
    // Do some work
    return this;
}

This you can write:

return new Foo().SomeMethod();

As a really extreme way of doing things if you can't change the methods you're calling, you could write an extension method:

public static T ExecuteAndReturn<T>(this T target, Action<T> action)
{
    action(target);
    return target;
}

Then you could write:

return new Foo().ExecuteAndReturn(f => f.SomeMethod());

But that's really foul. It would be far simpler to use a local variable in these cases...