c# – Get value from variable without passing parameter

Question:

I have the following method:

private string toCamelCase(string text)
{
    text = string.Format("{0}{1}",text.Substring(0, 1).ToLower(),text.Substring(1));
    return text;
}

To use it, I need to call it like this:

toCamelCase("OlaMundo");

I want it to work like this:

"OlaMundo".toCamelCase

Answer:

What you want is called an extension method . See the article on Wikipedia . And article in MSDN Magazine 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 namespace as the type you're using as the first parameter (yes, it's a parameter, even if it appears outside the method's parentheses, it's always like that in any method). It's not really that you need it, but it makes more sense that way if to help tools like Intellisense work better. In fact if you only want to use this method in specific circumstances then it is better to use another name. But most common is to use the same name as the original type so that this method is always available when the type is used.
  • It needs to be in a static class in addition to the method being static too. The class can have any name. It is common for programmers to suffix Extension or Ext 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.
  • It must have the this modifier before the first parameter that will be used with the object to be worked on. It's actually determined that object-first syntax can be used.
  • Avoid using first parameter types that can generate hierarchies. For example, avoid using object a lot, especially if it's in the Namespace System . If you do this, any data type will rely on your method as if it were native. This will pollute the method lookup table and make tools like Intellisense not as useful.
  • Be careful not to confuse it with a method that already exists in the type. The compiler has its rules for deciding which one to use but it may not be so clear to the programmer and create bugs that are time consuming to notice.
  • Prefer to extend types that you have no control over. If you can add a method inside the type, do it! So it makes very little sense for it to be private . I don't 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 it working on ideone . And in .NET Fiddle . I also put it on GitHub for future reference .

In the call the parentheses are still required.

"OlaMundo".toCamelCase();
Scroll to Top