What is the C# equivalent to Java’s isInstance()?
bool result = (obj is MyClass); // Better than using ‘as’
bool result = (obj is MyClass); // Better than using ‘as’
Class.isInstance does what you want. if (Point.class.isInstance(someObj)){ … } Of course, you shouldn’t use it if you could use instanceof instead, but for reflection scenarios it often comes in handy.
The only way you can do this check is if you have the Class object representing the type: Class<T> type; //maybe passed into the method if ( type.isInstance(obj) ) { //… }
The instanceof operator works on reference types, like Integer, and not on objects, like new Integer(213). You probably want something like clazz.isInstance(obj) Side note: your code will be more concise if you write public boolean isOf(Class clazz, Object obj){ return clazz.isInstance(obj) } Not really sure if you need a method anymore ,though.
You can apply another filter in order to keep only the ScheduleIntervalContainer instances, and adding a map will save you the later casts : scheduleIntervalContainers.stream() .filter(sc -> sc instanceof ScheduleIntervalContainer) .map (sc -> (ScheduleIntervalContainer) sc) .filter(sic -> sic.getStartTime() != sic.getEndTime()) .collect(Collectors.toList()); Or, as Holger commented, you can replace the lambda expressions with method references if … Read more
You might be interested in this entry from Steve Yegge’s Amazon blog: “when polymorphism fails”. Essentially he’s addressing cases like this, when polymorphism causes more trouble than it solves. The issue is that to use polymorphism you have to make the logic of “handle” part of each ‘switching’ class – i.e. Integer etc. in this … Read more
You can use Class.isArray() public static boolean isArray(Object obj) { return obj!=null && obj.getClass().isArray(); } This works for both object and primitive type arrays. For toString take a look at Arrays.toString. You’ll have to check the array type and call the appropriate toString method.
The reason that the performance of instanceof and getClass() == … is different is that they are doing different things. instanceof tests whether the object reference on the left-hand side (LHS) is an instance of the type on the right-hand side (RHS) or some subtype. getClass() == … tests whether the types are identical. So … Read more
Are you looking for: Super.class.isAssignableFrom(Sub.class)
The error message says it all. At runtime, the type is gone, there is no way to check for it. You could catch it by making a factory for your object like this: public static <T> MyObject<T> createMyObject(Class<T> type) { return new MyObject<T>(type); } And then in the object’s constructor store that type, so variable … Read more