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:
If you really, really have to use a method, then the only option is to make the method return the instance again:
This you can write:
As a really extreme way of doing things if you can't change the methods you're calling, you could write an extension method:
Then you could write:
But that's really foul. It would be far simpler to use a local variable in these cases...