top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Do you know Extension methods? Can we define extension methods for static class?

+5 votes
275 views
Do you know Extension methods? Can we define extension methods for static class?
posted Nov 17, 2015 by Manikandan J

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

In modern C#, it is possible to add extension methods that imitate instance methods, but not static methods.

There are quite a few use cases for this:

1.Direct API extension for popular static classes
Console , Assert , Path , etc.
This can be worked around if library authors switch to statically imported instance properties instead of classes, but it is extremely unlikely to be the right design choice for BCL APIs.

2.Polyfilling future functionality
At some point, TPL team was using TaskEx for future previews, since they couldn't extend Task -- complicating migration from preview to the real thing. And if someone wants to implement new Task.FromException in pre-4.6 .NET -- they are out of luck as well, unless they choose a different class name.

Design

Given the syntax currently used by instance methods, extending this to static doesn't feel straightforward.

One simple idea could be just to extend  [ExtensionAttribute] :

[Extension(typeof(Task))]
public static Task FromException(Exception ex) { ... }

But please feel free to propose better designs. And I assume C# team did have some potential design for this in mind then choosing the instance syntax?

Pros
1.Allows extension of static APIs, which is currently awkward
2.Allows polyfilling of static APIs, which is currently impossible

Cons
1.I don't have a good syntax proposal (though I personally would be just as happy with an attribute)

answer Nov 17, 2015 by Shivaranjini
Similar Questions
+1 vote

I want to build a class that perform various functions to the content(or lines) of any given file. I want to first include the opening and reading file function into that class, then add other methods.

Here is what I wrote for opening file and reading the lines:

class FileOpration:
 def __init__(self,name):
 self.name = name
 self.filename = self.name
 def readAllline(self):
 open(self.name).readlines()

file1 = FileOpration("myfile.txt")
print file1.filename
allines = file1.readAllline()
print allines

I define self.name variable because I want to store the specific file that I read. This works fine by the test code of print file1.filename. I saw "myfile.txt" on the terminal output.

However, the readAllline() method dose not work. The code only give me "None" as the output on terminal

...