views:

192

answers:

2

Given a group of objects that have a common set of properties and methods in support of given domain logic, is there a way of enforcing the presence of certain static methods on these objects?

I have concluded that implementing an interface does not achieve this (methods are instance only) and that static methods can not be marked override, virtual or abstract.

Thanks in advance.

+4  A: 

No.

(Note: In F# you can express such constraints using "inline" functions and "^" types (e.g. forall types T where T has a static method ToInt(T) that returns an 'int'). The compiler effectively auto-expands each call site to the specific type.)

Brian
thanks. I'm convinced.
sympatric greg
+3  A: 

The only way to force a type to have a static member is to inherit from it. All types will have the static members, and if you need to override them on a derived type you can use the "new" keyword:

static void Main(string[] args)
{
    Console.WriteLine(Base.Hello());
    Console.WriteLine(Derived.Hello());
    Console.Read();
    /* output will be:
    Hello
    World
    */
}

public class Base
{
    public static object Hello()
    {
        return "Hello";
    }
}

public class Derived : Base
{
    public static new object Hello()
    {
        return "World";
    }
}

It's not quite the same as abstract/override, but from a consumer standpoint, works similarly.

Rex M