Method to call a class when creating an instance?

I don’t know how to describe it better so that the name can be a little confusing.

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

For example, something like this:

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

I suppose I have seen something similar before, but I cannot find it. It is a little annoying to do something like ...

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

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

Thanks in advance!

+5
source share
7 answers

Well, if you have a property, you can use the object initializer:

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

, - :

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

:

return new Foo().SomeMethod();

, , , :

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

:

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

. ...

+15

SetName this, , .

+7

:

...

, - :

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

, SetName . . , :

MyClass newInstance new MyClass();
return newInstance.setName("some name");

, SetName , , .

, , this, , , , . , ... .

, , , :

public class MyClass
{
    public String name;
    public MyClass(String initialName)
    {
        name = initialName;
    }
}

:

MyClass instance = new MyClass("someName");
+7

. " ", .

SetName, :

public MyClass SetName(...)
{
    ...
    return this;
}

, .

, , :

return new MyClass().SetName("kkk").SetAge(44).SetAddres("...");

, .

+6

, :

public void SetName(String name) {
    this._name = name;
    return this;
}
+3

SetName , , this, . , SetName , #.

class MyClass {
    public int A {get;private set;}
    public int B {get;private set;}
    public MyClass SetA(int a) {
        A = a;
        return this;
    }
    public MyClass SetB(int b) {
        B = b;
        return this;
    }
}

:

return new MyClass().SetA(123).SetB(456);
+3

, factory, . :

MyClass.GetInstance.SetName("some name");

Not sure if this is what you want. Alternatively, why don't you call this method from the constructor and pass the necessary parameters through the constructor.

OR, the third option, build a factory class that processes all of these additional steps and returns an instance to you.

+1
source

All Articles