Search code examples
.netcom

Why is System.IO.Path (a class with only static members) COM visible?


Why is System.IO.Path COM visible when it contains only static members and fields?

[ComVisibleAttribute(true)]
public static class Path

I was under the impression that one cannot call static member functions of a COM object (and additionally, that the class would need a default constructor which Path does not have).

Also note SO user sharptooth comment:

It is also worth noting that it doesn't have Guid attribute which most likely means the class id will be regenerated each time it is compiled.

Why is PATH COM visible and what could be done with it?


Solution

  • Sure, this is a mistake. It is in good company, many other classes from mscorlib have the same problem. For example Registry, Directory, File, Buffer, Environment, Nullable, Monitor, Timeout. But not consistently, the attribute was properly omitted for BitConverter, Console, Convert, GC, Math, etcetera.

    The attribute is otherwise important for many classes in mscorlib, custom CLR hosts and scripting languages depend on it. Looks like the Microsoft programmer(s) that applied the attribute were just operating on auto-pilot. The mistake is inconsequential, Tlbexp knows how to deal with it. The coclass gets the [noncreatable] attribute so client programs cannot create an instance of the class. And the auto-generated interfaces are empty. So the type is simply not usable at all and you can't accidentally use it either.

    If you actually want to use System.IO.Path from a COM client program then you have to write a [ComVisible] wrapper class for it. Non-static of course, every method you write can simply delegate directly to the one of the Path methods. You'd like the [appobject] attribute on the coclass so it behaves statically in a client program that supports the attribute, sadly .NET doesn't have an attribute for it.