Reputation: 14573
I saw this code:
this.CreateGraphics().DrawRectangle( Pens.Black, new Rectangle( 0, 0, 200, 100 ) );
CreateGraphics()
is a method, but it acts like a class with static voids. How can I create this in my code? I don't know how this technique can be called...
Upvotes: 0
Views: 1059
Reputation: 27584
This is called Factory Method (it's one of design patterns). Basically you create a method which will return new instances of class e.g.:
public class Graphics
{
public static Graphics CreateGraphics()
{
return new Graphics();
}
// ... other methods etc ...
public bool OtherMethod()
{
return false;
}
}
// then you can do Graphics.CreateGraphics().OtherMethod();
UPDATE
You can use this design patter in other places, all you need to do is to create a method which will return new instance of class (CreateGraphics
method):
public class MyClass
{
public static Graphics CreateGraphics()
{
return new Graphics();
}
// ... other methods etc ...
public void MyOtherMethod()
{
this.CreateGraphics().Something();
}
}
Upvotes: 2
Reputation: 14672
CreateGraphics() is returning an instance of the Graphics class.
I suspect you are talking about the Control.CreateGraphics() method,
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.creategraphics.aspx
Any method that returns an instance of an object like this, can be used in this way.
Upvotes: 0