C# “as” cast vs classic cast [duplicate]

With the “classic” method, if the cast fails, an InvalidCastException is thrown. With the as method, it results in null, which can be checked for, and avoid an exception being thrown. Also, you can only use as with reference types, so if you are typecasting to a value type, you must still use the “classic” … Read more

Cast Object to Generic Type for returning

You have to use a Class instance because of the generic type erasure during compilation. public static <T> T convertInstanceOfObject(Object o, Class<T> clazz) { try { return clazz.cast(o); } catch(ClassCastException e) { return null; } } The declaration of that method is: public T cast(Object o) This can also be used for array types. It … Read more

Why does “The C Programming Language” book say I must cast malloc?

From http://computer-programming-forum.com/47-c-language/a9c4a586c7dcd3fe.htm: In pre-ANSI C — as described in K&R-1 — malloc() returned a char * and it was necessary to cast its return value in all cases where the receiving variable was not also a char *. The new void * type in Standard C makes these contortions unnecessary. To save anybody from the … Read more

In C, why do some people cast the pointer before freeing it?

Casting may be required to resolve compiler warnings if the pointers are const. Here is an example of code that causes a warning without casting the argument of free: const float* velocity = malloc(2*sizeof(float)); free(velocity); And the compiler (gcc 4.8.3) says: main.c: In function ‘main’: main.c:9:5: warning: passing argument 1 of ‘free’ discards ‘const’ qualifier … Read more

Assignment in an if statement

The answer below was written years ago and updated over time. As of C# 7, you can use pattern matching: if (animal is Dog dog) { // Use dog here } Note that dog is still in scope after the if statement, but isn’t definitely assigned. No, there isn’t. It’s more idiomatic to write this … Read more

dynamic_cast and static_cast in C++

Here’s a rundown on static_cast<> and dynamic_cast<> specifically as they pertain to pointers. This is just a 101-level rundown, it does not cover all the intricacies. static_cast< Type* >(ptr) This takes the pointer in ptr and tries to safely cast it to a pointer of type Type*. This cast is done at compile time. It … Read more

How to insert a character in a string at a certain position?

As mentioned in comments, a StringBuilder is probably a faster implementation than using a StringBuffer. As mentioned in the Java docs: This class provides an API compatible with StringBuffer, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being … Read more