Jun 20

The C# compiler is really smart, but…

Posted in Uncategorized      Comments Off on The C# compiler is really smart, but…

I’m still not understanding why it won’t give me a warning when I create an internal class with a public method. Here’s an example:

class MyInternalClass{
   public void Test(){} //no compiler warning

Ok, at the end of the day, Test is really an “internal” method since the acessibility of a member can never be greater than the one of its containing type. But why can’t I get at least a warning? In this case, setting the method type to internal should be the “maximum” accesibility,right? There are other similar scenarios where we get the correct response from the compiler. For instance, you cannot declare a protected method on a struct. This makes sense, of course, because you can not inherit from a struct (therefore, you really don’t need to declare protected methods).

So, here we are: on the one hand, the compiler will let me declare a method as public on an internal class, even though that method will only end up beeing used on the assembly where it is defined due to the accessibility of its containing type without even generating a warning. On the other hand,the compiler won’t “relax” the protected method error on a struct type.

I’m not a compiler geek (or even a C# language expert) so the problem might really be on spec and not on the compiler. Anyway,I think that the compiler could at least generate a warning on these scenarios (internal classes with public methods). And what do you think?