Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if a Type is a static class? [duplicate]

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

like image 406
Binary Worrier Avatar asked Nov 10 '10 13:11

Binary Worrier


2 Answers

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

like image 68
jasper Avatar answered Sep 20 '22 13:09

jasper


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
    }
like image 34
Stefan P. Avatar answered Sep 21 '22 13:09

Stefan P.