Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# static abstract properties cannot be overwritten by child interface

Tags:

c#

.net

.net-7.0

I am trying to work with static abstract properties that were introduced in .NET 7. here is an example of what i am trying to achieve:

public interface IRegister
{
    public static abstract byte RegisterCode { get; }
    public static abstract int BitsSize { get; }
}

public interface IRegister8Bit : IRegister
{
    public static new int BitsSize => 8;
}

public class T : IRegister
{
    public static byte RegisterCode => 0x01;
    public static int BitsSize => 16;
}

public class T2 : IRegister8Bit
{
    public static byte RegisterCode => 0x07;
}

public class Program
{
    public static void Test<Register>() where Register : IRegister
    {
        Console.WriteLine(Register.RegisterCode);
        Console.WriteLine(Register.BitsSize);
    }
    
    public static void Main()
    {
        Test<T>();
        Test<T2>();
    }
}

But I get the following compile error:

Compilation error (line 20, col 19): 'T2' does not implement interface member 'IRegister.BitsSize'

why is T2 still requesting me to explicitly implement BitsSize even though it is implemented in the parent interface IRegister8Bit ?

like image 350
Meydan Ozeri Avatar asked Mar 05 '26 22:03

Meydan Ozeri


1 Answers

You can provide explicit interface implementation for the static abstract method:

public interface IRegister8Bit : IRegister
{
     static int IRegister.BitsSize => 8;
}

Then T2 will compile:

public class T2 : IRegister8Bit
{
    public static byte RegisterCode => 0x07;
}

This has downside though, BitsSize will not be accessible by the type name so the generic indirection approach should be used:

// for T both props work
Console.WriteLine(T.RegisterCode);
Console.WriteLine(T.BitsSize);

// for T2 only RegisterCode is accessible:
Console.WriteLine(T2.RegisterCode);
// Console.WriteLine(T2.BitsSize); // will not compile
Console.WriteLine(GetBitSize<T2>());

// generic indirection method:
int GetBitSize<T>() where T : IRegister => T.BitsSize; 
like image 157
Guru Stron Avatar answered Mar 08 '26 22:03

Guru Stron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!