Question

How is it possible to make prototype methods in C#.Net?

In JavaScript, I can do the following to create a trim method for the string object:

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
}

How can I go about doing this in C#.Net?

Was it helpful?

Solution

You can't dynamically add methods to existing objects or classes in .NET, except by changing the source for that class.

You can, however, in C# 3.0, use extension methods, which look like new methods, but are compile-time magic.

To do this for your code:

public static class StringExtensions
{
    public static String trim(this String s)
    {
        return s.Trim();
    }
}

To use it:

String s = "  Test  ";
s = s.trim();

This looks like a new method, but will compile the exact same way as this code:

String s = "  Test  ";
s = StringExtensions.trim(s);

What exactly are you trying to accomplish? Perhaps there are better ways of doing what you want?

OTHER TIPS

It sounds like you're talking about C#'s Extension Methods. You add functionality to existing classes by inserting the "this" keyword before the first parameter. The method has to be a static method in a static class. Strings in .NET already have a "Trim" method, so I'll use another example.

public static class MyStringEtensions
{
    public static bool ContainsMabster(this string s)
    {
        return s.Contains("Mabster");
    }
}

So now every string has a tremendously useful ContainsMabster method, which I can use like this:

if ("Why hello there, Mabster!".ContainsMabster()) { /* ... */ }

Note that you can also add extension methods to interfaces (eg IList), which means that any class implementing that interface will also pick up that new method.

Any extra parameters you declare in the extension method (after the first "this" parameter) are treated as normal parameters.

You need to create an extension method, which requires .NET 3.5. The method needs to be static, in a static class. The first parameter of the method needs to be prefixed with "this" in the signature.

public static string MyMethod(this string input)
{
    // do things
}

You can then call it like

"asdfas".MyMethod();

Using the 3.5 compiler you can use an Extension Method:

public static void Trim(this string s)
{
  // implementation
}

You can use this on a CLR 2.0 targeted project (3.5 compiler) by including this hack:

namespace System.Runtime.CompilerServices
{
  [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly)]
  public sealed class ExtensionAttribute : Attribute
  {
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top