Extension methods in C# and Ruby
Extending classes with new methods is a pretty useful feature of object-oriented programming languages. However, implementation of extension methods can be more or less simple and elegant. Today I would like to compare implementation of extension methods in C# and Ruby.
C# extension methods
Let’s consider the following example class.
public class ExampleClass
{
public string GetName()
{
return "Mikołaj";
}
}
To extend it with a new method we have to implement another independent static class, which has an implementation of our extension method.
public static class ExampleClassExtensions
{
public static string Greet(this ExampleClass exampleClass)
{
var name = exampleClass.GetName();
return $"Hello {name}!";
}
}
There are two important things. The first parameter of the extension method have to be preceded by the this
keyword and should be of the type on which the method is operating.
ExampleClassExtensions
can be named anything you like. It may also contain extension methods for classes other than ExampleClass
. I named it so as to keep a clear naming convention.
The Ruby way
Okay, so let’s start with our example class which will be extended with extra method.
class ExampleClass
def get_name
"Mikołaj"
end
end
Implementation of an extension method is as simple as redefining our ExampleClass with an extra method. Take a look:
class ExampleClass
def greet
"Hello #{self.get_name}!"
end
end
That’s it. Super simple.
Which one I consider to be better?
I really like simple solutions, so at first glance Ruby extension methods implementation seems better to me.
On the other hand, the C# solution does not directly modify the class being extended. The notation is more complicated, but it provides a separation between the class and its extensions.
It’s hard for me to decide which solution is better. I’m just getting started with Ruby, and I have plans to study its object model better. I think it is too early to express my opinion on this.
If you have any interesting thoughts on this topic, please let me know!