How many interfaces are allowed to be implemented?
Asked Answered
F

6

27

In C#:

How many interfaces a class can implement at the same time?

public class MyClass: IInteferface_1, IInterface_2, ... , IInterface_N
{
}

Is there a limit for N?

Don't worry I don't want to implement or maintain such an object. I was just wondering if there is a limit.

Flowerpot answered 26/11, 2010 at 13:16 Comment(1)
I think this is a perfectly valid question because the answer will not only help understand the limitations of the language, but it may also help a programmer decide how to structure their code.Reserve
M
48

The C# language imposes no limit on the number of interfaces. There are two practical limits though.

First, as chibacity points out, the compiler will eventually run out of heap or stack space when processing large numbers of interfaces, or extremely deep hierarchies of interfaces.

Even if we fixed those problems, there would still be a second issue. Interface implementation is encoded in metadata in the InterfaceImpl table. Metadata tables typically can have no more than 2^24 members, so the total number of interfaces implemented by all types in an assembly must be less than about 16 million.

Obviously you are going to never run into these limitations in practice. Don't worry about it.

Mercator answered 26/11, 2010 at 16:11 Comment(6)
@Eric: do you know why the limit is 2^24? Just curious why that number. Is it related to the type used in the metadata tables themselves that is limited to 2^24?Stoup
@Joan: Eric is part of the C# language team at MS, so even if the metadata limit isn't documented (e.g. in the ECMA standards) he has inside information.Lubricator
@Richard, I know he is and believe him for sure, just wondering why it's 2^24. If it was 2^32 then I would imagine this has to do with Int32, just curious where 2^24 comes from.Stoup
@Joan: good question. A metadata token is a four-byte integer where the top byte identifies the kind of token. So for example a "TypeDef" token has top byte 0x02. That leaves 24 bits for the rest of the token.Mercator
@Eric: Thanks Eric for explaining it. Now I know why :OStoup
There's an earlier limit that's hit, a type cannot have more than 65536 members. C++ programmers regularly run into it when they flip the /clr option on all their code and get their non-managed functions and globals crammed into one super class. I thought it was the metadata token but it doesn't seem to be after checking 335.Synthiasyntonic
A
15

The number of interfaces you can implement is limited by what the compiler can handle. Too many interfaces results in a stackoverflow exception in the C# compiler (error CS1647). This would lead me to believe that there is no fixed limit, but that under certain conditions the compiler will simply bomb i.e. the number will be dependant on what stack space is available when the compiler is handling the class.

The limit is likely to be compiler version dependant too. The following code can be used to generate a test case for probing the limit.

    int iterations = (int)Math.Pow(2, 8) + 1;

    Func<int, string> getInterfaceName = i => "I" + i;

    StringBuilder sb = new StringBuilder();

    sb.AppendLine("using NUnit.Framework;");
    sb.AppendLine("[TestFixture]");

    sb.AppendLine("public class Test");
    sb.AppendLine("{");

    sb.AppendLine("[Test]");
    sb.AppendLine("public void bling()");
    sb.AppendLine("{");
    sb.AppendLine("Class1 class1 = new Class1();");

    for (int i = 0; i < iterations; i++)
    {
        sb.AppendLine(getInterfaceName(i) + " int" + i + " = class1;");
        sb.AppendLine("int" + i + ".Bling();");
    }

    sb.AppendLine("}");

    for (int i = 0; i < iterations; i++)
    {
        sb.AppendLine("public interface " + getInterfaceName(i) + " { void Bling(); }");
    }

    sb.Append("public class Class1 : " + getInterfaceName(0));

    for (int i = 1; i < iterations; i++)
    {
        sb.Append(", " + getInterfaceName(i));
    }

    sb.Append("{ public void Bling(){} }");

    sb.AppendLine("}");

    File.WriteAllText(@"C:\tmp.cs", sb.ToString());
Angleworm answered 26/11, 2010 at 15:42 Comment(1)
Oh god. Scripting in C#.Diurnal
M
8

If you're asking this question with a view to actually implementing a LOT of interfaces, I'd say you have a serious design problem.

As far as I know, there is no limit other than your computer's memory.

Mastermind answered 26/11, 2010 at 13:18 Comment(4)
+1 because your answer made me titter. And because it's true.Sulphonate
Also as far as I know there is no limit but not sure.Flowerpot
Well Liviu, I did a quick search but its hard to find a definite answer because its not a common question. So no, I can't be sure that there isnt an absolute limit. Maybe you could do some tests and find out :-)Mastermind
It seems there is a perfectly valid reason to have a class that implements thousands of interfaces. Just take a look at how Jab dependency injection framework generates ServiceResolver at compile time: github.com/pakrym/jabWyatan
P
1

Consider what it actually means to the compiler / run time to say MyClass: IInteferface_1, IInterface_2, ... , IInterface_N. There is no design time limit as the compiler simply makes sure that your class has appropriate (method) signatures for each interface its supposed to implement. As for a run time limit, I don't think memory has much impact as any reference to your class via an interface it implements (as verified at design time) would simply make sure your class has the appropriate method signature for that interface. If the object doesn't implement the interface, the object would just lack the method signature.

Psalm answered 26/11, 2010 at 13:57 Comment(0)
O
1

I just checked the current version of the Microsoft C♯ Language Specification Version 4.0, and there is no mention of a limit in §1.6.4, §1.9, §10.1.4, §10.1.4.2 and §13. There is also no syntactic limit in the grammar in §B.2.7.

I obviously didn't read the entire 500 pages, but I don't know where else in that document a limit might be mentioned.

Note: this only applies to Microsoft C♯, and only to Version 4.0. I didn't check earlier versions of Microsoft C♯, nor did I check ECMA/ISO C♯. Also, it only applies to C♯, there might be limits in the CLI.

And last but not least, there might be implementation-specific limits in both Microsoft Visual C♯ and Novell Mono C♯, as well implementation-specific limits in Microsoft's and Mono's implementations of the CLI (i.e. the CLR and the Mono VM).

However, the question was about C♯, not about any particular implementation of C♯ and not about the CLI, so I feel pretty confident in claiming that the number of interfaces a class can implement is unbounded.

Overlie answered 26/11, 2010 at 15:33 Comment(0)
F
-7

There is a limit

You are limited to 255 as a single byte is used as an indexer by the JIT to the type table for the relevant interface.

Fishbein answered 26/11, 2010 at 13:32 Comment(10)
Finally a scientific answer (+1), can somebody confirm?Flowerpot
Whould you reference to some articles?Rudy
-1 I ran a little experiment and was able to compile a class that implemented 10 * 1000 interfaces, so the 256 limit is incorrect.Angleworm
Its not a compiler limitation, but a JIT limitation - try running it in an app that has code that utilizes the class polymorphicaly via more than 255 interfacesFishbein
@Dean Another quick test. Successfully constructed a class that implemented 257 interfaces, and accessed the class through each of the interfaces. No problem.Angleworm
well, I read about it in a MS book on CLR a few years back - very strange !Fishbein
@chibacity For the tests I want to give you the accepted answer if you provide one.Flowerpot
@Dean - maybe it is true for an older version then?Mastermind
I need to try and find that book again - I was quite sure of my answer so it'll be interesting to get to the bottom of itFishbein
Where does your assumption come from?Countable

© 2022 - 2024 — McMap. All rights reserved.