Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create Prototype Methods (like JavaScript) in C#.Net?

Tags:

c#

.net

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?

like image 806
GateKiller Avatar asked Aug 07 '08 12:08

GateKiller


2 Answers

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?

like image 113
Lasse V. Karlsen Avatar answered Oct 10 '22 21:10

Lasse V. Karlsen


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.

like image 35
Matt Hamilton Avatar answered Oct 10 '22 20:10

Matt Hamilton