This is an example of a factory method. (Which can often be a step toward using a separate factory object.)
Somewhere in XmlReader.Create it is internally making use of the new keyword. In order to instantiate a new instance of an object, you need to use new to call a constructor. To reduce coupling between objects, however, you may abstract that behind a factory method or factory object.
For example, these two implementations do roughly the same thing:
public class Widget
{
public Widget() { }
}
//... elsewhere ...
var widget = new Widget();
And:
public class Widget
{
private Widget() { }
public static Widget Create()
{
return new Widget();
}
}
//... elsewhere ...
var widget = Widget.Create();
In an example this simple, there's little difference between the two. As code evolves and becomes more complex, there can be a number of compelling reasons to choose one over the other. For example:
- There are complex constructors and you want to expose a simple interface for building an instance.
- The constructors are likely to change often and you want consumers of your library to have a single unchanging interface.
- There is significant logic invoked when building an object and you want to move that logic to its own object.
- You want to use a separate object for mockability in automated testing.
- You have a more complex inheritance structure and want to expose a top-level abstract factory.
- etc.
newcall).