tags:

views:

108

answers:

3

I know that virtual and static methods are opposing concepts, but I think that it could make sense sometimes to use them together. There have been quite a bunch of similiar question on SO on this topic, but the following scenario has not been covered yet.

There's a C# interface that looks like this:

interface IVertexMeshLoader
{
    VertexMesh LoadFromFile(string fname);
}

An implementation of that could look like this:

class VertexMeshLoaderObj : IVertexMeshLoader
{
    public VertexMesh LoadFromFile(string fname) { .. }
}

Now I would like to be able to call method without an object instance, but I cannot make the LoadFromFile() method static, because it implements the interface.

The best solution I worked out so far is to write a static method LoadFromFileStatic() that contains the actual code. The LoadFromFile() then just calls it. Not very pretty, imho.

I could also create an instance of VertexMeshLoadObj every time I want to call the method, but that is even worse.

Are there better ways? Thanks :-)

A: 

If you must do this, create a singleton instance of IVertexMeshLoader and access that

mcintyre321
+2  A: 

Here's another option. Provide an explicit implementation of the interface which just calls the static method. It allows them to have the same name

class VertexMeshLoaderObj : IVertexMeshLoader
{
  VertexMesh IVertexMeshLoader.LoadFromFile(string fname) { 
    LoadFromFile(fname);
  }
  public static VertexMesh LoadFromFile(fname) {
    ...
  }
}
JaredPar
The `public` is not valid for explicit implementation, but it works like a breeze without. Thanks!
A: 

Even if you're only interested in the vtable of the object and not in the actual members, you need an object instance to know what method to call.

So even if the actual implementation doesn't seem to depend on the instance, it in fact does.

You're not using "static virtual" methods but really virtual ones.

Alexandre C.