Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if a type is static

Let's say I have a Type called type.

I want to determine if I can do this with my type (without actually doing this to each type):

If type is System.Windows.Point then I could do this:

Point point1 = new Point(); 

However if type is System.Environment then this will not fly:

Environment environment1 = new Environment(); //wrong 

So if I am iterating through every visible type in an assembly how do I skip all the types that will fail to create an instance like the second one? I'm kind of new to reflection so I'm not that great with the terminology yet. Hopefully what I'm trying to do here is pretty clear.

like image 505
Beaker Avatar asked Jul 24 '09 05:07

Beaker


People also ask

How do I check if a method is static C#?

Use Modifier. isStatic(method. getModifiers()) . Note: This method is actually dangerous from a security standpoint.

What is a static class?

A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new operator to create a variable of the class type.

What are static classes C#?

A static class in C# is a class that cannot be instantiated. A static class can only contain static data members including static methods, static constructors, and static properties. In C#, a static class is a class that cannot be instantiated.

Why static class is used in C#?

Static classes and static members are useful because they do not require instances created for each new object. That means, they consume fewer resources and no duplication of the same class or member is needed in memory. Static members make code cleaner.


1 Answers

static classes are declared abstract and sealed at the IL level. So, you can check IsAbstract property to handle both abstract classes and static classes in one go (for your use case).

However, abstract classes are not the only types you can't instantiate directly. You should check for things like interfaces (without the CoClass attribute) and types that don't have a constructor accessible by the calling code.

like image 140
mmx Avatar answered Oct 12 '22 02:10

mmx