4

How Can I Make Extension Method For System.IO.Path Class what i mean that i need something like below:

Path.GetExtension(sFilePath) 

i want to make method:

Path.GetMimeType(sFilePath)

Extension Method:

public static string GetMIMEType(this Path sPath,string sFilePath)
{
        string sExtension = Path.GetExtension(sFilePath).ToLowerInvariant();

        if (sExtension.Length > 0 && dicMIMETypes.ContainsKey(sExtension.Remove(0, 1)))
        {
            return dicMIMETypes[sExtension.Remove(0, 1)];
        }
        return "unknown/unknown";
}

but when compile above code method get error ('System.IO.Path': static types cannot be used as parameters).

Thanks All,

  • 1
    Not possible -- but this answer has a workout that may suit your needs. http://stackoverflow.com/questions/249222/can-i-add-extension-methods-to-an-existing-static-class – George Johnston Jul 17 '13 at 20:21
  • 3
    You can tell you are doing it wrong, you never actually use the *sPath* argument in your code. Nor is there a way you'll figure out how to use it. So there's no point to the extension method, it doesn't extend anything. – Hans Passant Jul 17 '13 at 20:41

2 Answers2

5

Path is static, and therefore you cannot create an extension method for it. Extension methods require an instance of an object.

Haney
  • 32,775
  • 8
  • 59
  • 68
3

This feature is currently not available. you can add extension methods only to an Instance not to Class itself(static).

Feature request already given to Microsoft Static extension methods in C# 4.0 it is not implemented and They may consider it in future or may not.

Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
  • Note that "won't fix" doesn't necessarily mean "will never fix". It just means that Microsoft has decided that the time is not right, right now. I've seen "won't fix" cases before that has eventually been fixed/changed, so it's not a "never". I don't necessarily agree with this way of closing the case, but it may cut down on the amount of noise they have, I still have some open cases on other produces and they get the odd "I want this too" every week or so, cluttering up my mailbox. In can only imagine what the developers mailbox would look like with such a system. – Lasse V. Karlsen Jul 17 '13 at 20:45
  • 2
    Just FYI, that link no longer links to anything meaningful. – Broots Waymb Feb 12 '19 at 18:44