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?
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.
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.
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...
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.
You have two type identifiers, you just need to compare the types.
if(typeof(T) == typeof(ArgumentNullException))
{
...
}
If inherited types should be respected, use:
if(typeof(ArgumentNullException).IsAssignableFrom(typeof(T)))
{
...
}
if (typeof(T) == typeof(ArgumentNullException))
{
//your code
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With