I was playing little bit with classes. Idea is to see how it will behave if we declare method with type as current class instance to which this method belong.
So, I have declared class like:
public class MyClass
{
public string mOne = "none";
public string mTwo = "none";
public string mAll = "none";
public MyClass MyMethodOne()
{
this.mOne = "I am from method one";
this.mAll = "My name is all and I am also from method one";
return this;
}
public MyClass MyMethodTwo()
{
this.mTwo = "I am from method two";
this.mAll = "My name is all and I am also from method two";
return this;
}
public MyClass MyMethodNewInstanceOne()
{
MyClass something = new MyClass();
something.mOne = "I am from method one";
something.mAll = "My name is all and I am also from method one";
return this;
}
public MyClass MyMethodNewInstanceTwo()
{
MyClass something = new MyClass();
something.mTwo = "I am from method two";
something.mAll = "My name is all and I am also from method two";
return something;
}
}
Notice for example:
this.mTwo = "I am from method two";
return this;
Here we are not creating new instance, so if we do call like:
MyClass myClassesResult = playingWithClasses.MyMethodOne().MyMethodTwo();
We will not loose any changes
That means that if we create console application like:
MyClass playingWithClasses = new MyClass();
MyClass myClassesResult = playingWithClasses.MyMethodOne().MyMethodTwo();
Console.WriteLine("************* without new instance *************");
Console.WriteLine("One: " + myClassesResult.mOne);
Console.WriteLine("Two: " + myClassesResult.mTwo);
Console.WriteLine("All: " + myClassesResult.mAll);
Result will be like:
************* without new instance *************
One: I am from method one
Two: I am from method two
All: My name is all and I am also from method two
Then notice for example:
MyClass something = new MyClass();
something.mTwo = "I am from method two";
return something;
That means that if we create console application like:
MyClass playingWithClasses = new MyClass();
MyClass myClassesNewInstanceResult = playingWithClasses.MyMethodNewInstanceOne().MyMethodNewInstanceTwo();
Console.WriteLine("************* with new instance *************");
Console.WriteLine("One: " + myClassesNewInstanceResult.mOne);
Console.WriteLine("Two: " + myClassesNewInstanceResult.mTwo);
Console.WriteLine("All: " + myClassesNewInstanceResult.mAll);
Result will be like:
************* with new instance *************
One: none
Two: I am from method two
All: My name is all and I am also from method two
Example project you can download from here.