As per MSDN, Extension methods
can be defined "inside a non-nested, non-generic static class".
In this particular case, you can add it to a static BuilderUtilities
class.
Pregunta
I'm trying to follow along this article: http://codebetter.com/gregyoung/2007/12/05/a-use-for-extension-methods/
I follow along fine up to this point:
Now that I have these I can decorate the Builder with extension methods like:
public static CostBuilder Cost(this Builder s)
{
return new CostBuilder();
}
Where do I stick this piece of code?
EDIT: Per vlad's answer
I stuck this code where the Builder and Create class was
public static partial class BuilderExtensions
{
}
Then for any namespace that needs to have the builder added, I stuck this beneath the builder class in the same class file:
public static partial class BuilderExtensions
{
public static CostBuilder Cost(this Builder s)
{
return new CostBuilder();
}
}
Solución
As per MSDN, Extension methods
can be defined "inside a non-nested, non-generic static class".
In this particular case, you can add it to a static BuilderUtilities
class.
Otros consejos
Extension methods must be placed in static classes.
public static class BuilderExtensions {
public static CostBuilder Cost(this Builder s) {
return new CostBuilder();
}
}
You can change the public
keyword in the BuilderExtensions
declaration to internal
to keep the extension methods invisible to consumers of your API.