14

Possible Duplicate:
Determine if a type is static

Duplicate of Determine if a type is static

Is there a property/attribute I can inspect to see if a System.Type is a static class?

I can do this indirectly, by testing that the Type has static methods, and no instance methods beyond those inherited from System.Object, however it doesn't feel clean (I've a sneaking suspicion I'm missing something and this isn't a rigorous enough definition of static class).

Is there something I'm missing on the type that will categorically tell me this is a static class?

Or is static class c# syntax sugar and there's no way to express it in IL?

Thanks
BW

Community
  • 1
  • 1
Binary Worrier
  • 50,774
  • 20
  • 136
  • 184
  • 2
    Determine if a type is static: http://stackoverflow.com/questions/1175888/determine-if-a-type-is-static – CD.. Nov 10 '10 at 13:50
  • It's mostly C# syntax. What do you need to detect it for? – Gabe Nov 10 '10 at 13:50
  • @CD: How the hell did I miss that, I searched extensively before posting the question. Master, your search-fu is greater than mine :) – Binary Worrier Nov 10 '10 at 13:55
  • @Gabe: I want to automatically generate Interfaces and instance classes that map directly to static classes (e.g. File & Directory in System.IO.File, and MANY legacy static classes in our code base. I'm trying to introduce Unit testing and these are a major road block to using Mocks for tests. If I can I'll auto generate wrappers, far too much to do to hand-code them. – Binary Worrier Nov 10 '10 at 13:59
  • 2
    First time I've voted to close my own question *sigh* – Binary Worrier Nov 10 '10 at 14:00

3 Answers3

16

yea, you need to test for both IsAbstract and IsSealed. A non static class can never be both. Not fantastic but it works.

jasper
  • 3,424
  • 1
  • 25
  • 46
9

At IL level any static class is abstract and sealed. So you can do something like this:

    Type myType = typeof(Form1);
    if (myType.GetConstructor(Type.EmptyTypes) == null && myType.IsAbstract && myType.IsSealed)
    {
        // class is static
    }
Stefan P.
  • 9,489
  • 6
  • 29
  • 43
3
        if (typeof(C).Attributes.HasFlag(System.Reflection.TypeAttributes.Abstract) &&
             typeof(C).Attributes.HasFlag(System.Reflection.TypeAttributes.Sealed) && 
            typeof(C).Attributes.HasFlag(System.Reflection.TypeAttributes.Class) )
            {
            }

but may be there is a class with this attributes but it's not static

Saeed Amiri
  • 22,252
  • 5
  • 45
  • 83