Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c#: Inherited/interface static member?

Is there a way to require that a class have a particular abstract member? Something like this:

public interface IMaxLength
{
    public static uint MaxLength { get; }
}

Or perhaps this:

public abstract class ComplexString
{
    public abstract static uint MaxLength { get; }
}

I'd like a way enforce that a type (either through inheritance or an interface?) have a static member. Can this be done?

like image 942
core Avatar asked Nov 22 '25 08:11

core


1 Answers

You could create a custom attribute that allows enforcing the requirement as a runtime guarantee. This is not a fully complete code sample (you need to call VerifyStaticInterfaces in your application startup, and you need to fill in the marked TODO) but it does show the essentials.

I'm assuming you're asking this so you can guarantee successful reflection-based calls to named methods.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false, AllowMultiple = true)]
internal sealed class StaticInterfaceAttribute : Attribute
{
    private readonly Type interfaceType;

    // This is a positional argument
    public StaticInterfaceAttribute(Type interfaceType)
    {
        this.interfaceType = interfaceType;
    }

    public Type InterfaceType
    {
        get
        {
            return this.interfaceType;
        }
    }

    public static void VerifyStaticInterfaces()
    {
        Assembly assembly = typeof(StaticInterfaceAttribute).Assembly;
        Type[] types = assembly.GetTypes();
        foreach (Type t in types)
        {
            foreach (StaticInterfaceAttribute staticInterface in t.GetCustomAttributes(typeof(StaticInterfaceAttribute), false))
            {
                VerifyImplementation(t, staticInterface);
            }
        }
    }

    private static void VerifyInterface(Type type, Type interfaceType)
    {
        // TODO: throw TypeLoadException? if `type` does not implement the members of `interfaceType` as public static members.
    }
}

internal interface IMaxLength
{
    uint MaxLength
    {
        get;
    }
}

[StaticInterface(typeof(IMaxLength))]
internal class ComplexString
{
    public static uint MaxLength
    {
        get
        {
            return 0;
        }
    }
}
like image 64
Sam Harwell Avatar answered Nov 24 '25 01:11

Sam Harwell