Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare class type without instance

I have a 'factory' class that should compare the generic class type parameter and return a specific instance of an object:

public static class MyExceptionFactory<T> where T: System.Exception {
    public static MyReturnObj Create() {
        // return instance of MyReturnObj based on type of T
    }
}

But I can't check if e.g. T is ArgumentNullException because T is a type parameter and not a variable

if(T is ArgumentNullException) // won't work

.. and also, I can't check for the type of T

if(typeof(T) is ArgumentNullException)

because IntelliSense tells me that T is never System.ArgumentNullException (I assume because T is System.Exception)

How could I solve this? Do I have to pass an instance of a System.Exception to check it's type or is there any other way to do it via class type parameter?

like image 462
Atrotygma Avatar asked Aug 06 '13 08:08

Atrotygma


People also ask

How to compare 2 objects of generic class type without knowing properties?

But I will explain how to compare 2 objects of generic class type without knowing their properties in this article. Step 1 : Create a console application and add class Student with the properties as below. Step-2: Add objects for students as below in the Main method. Step-3: Now I want to compare these above student objects with each other.

How to compare two objects with different types in Java?

If you have two objects and you want to compare their types with each other, you can use: if (obj1.getClass () == obj2.getClass ()) { // Both have the same type } If you had two Strings and compared them using == by calling the getClass () method on them, it would return true. What you get is a reference on the same object.

Why is there two instances of the same class in Java?

This is because they are both references on the same class object. This is true for all classes in a java application. Java only loads the class once, so you have only one instance of a given class at a given time. Hmmm...

How to get the class object of its type in Java?

The Object.getClass () method is an instance method of the Object class. If we have an object, we can call object.getClass () to get the Class object of its type. Similarly, we can use the ClassName.class syntax to get the Class object of the type.


Video Answer


3 Answers

You have two type identifiers, you just need to compare the types.

if(typeof(T) == typeof(ArgumentNullException))
{
   ...
}
like image 161
nvoigt Avatar answered Sep 28 '22 10:09

nvoigt


If inherited types should be respected, use:

if(typeof(ArgumentNullException).IsAssignableFrom(typeof(T)))
{
...
}
like image 40
Thomas B. Avatar answered Sep 28 '22 12:09

Thomas B.


if (typeof(T) == typeof(ArgumentNullException))
{
    //your code
}
like image 44
Guru Stron Avatar answered Sep 28 '22 10:09

Guru Stron