What you're calling is extension method . See the Wikipedia article . And MSDN Magazine article in Portuguese (it's in VB.Net but it's the same thing).
He needs to follow some rules:
- It needs to be in the same%% of the type you are using as the first parameter (yes, it is a parameter, even though it appears outside the parentheses of the method, this is always the case in any method). It's not that much of a need, but it makes more sense if you help tools like Intellisense work better. In fact if you want to use this method only in specific circumstances then it is better to use another name. But the most common is to use the same name as the original type so this method is always available when the type is used.
- It needs to be in a static class besides the static method as well. The class can have any name. It is common for programmers to put the suffix
namespace
or Extension
to indicate that it is a class that contains extension methods. You can put any static method in there but ideally just put extension methods that are related to each other.
- Must have the
Ext
modifier before the first parameter to be used with the object to be worked on. It is really determined that object syntax can first be used.
- Avoid using first parameter types that can generate hierarchies. For example, avoid using
this
, especially if object
. If you do this any kind of data will count on your method as if it were native. This will pollute the lookup table of methods and will make tools like Intellisense not so useful.
- Be careful not to confuse with an existing method in type. The compiler has its rules for deciding which one to use but may not be as clear to the programmer and create time-consuming bugs .
- Prefer to extend types that you have no control over. If you can add a method inside the type, do it! Therefore, it makes little sense that he is
Namespace System
. I do not even know if it works (I think so).
Example:
namespace System {
public static StringExt {
public static string ToCamelCase(this string text) {
return string.Format("{0}{1}", text.Substring(0, 1).ToLower(), text.Substring(1));
}
}
}
See running on .NET Fiddle . And no Coding Ground . Also put it in GitHub for future reference .
In the call, the parenthesis is still needed.
"OlaMundo".toCamelCase();