Extension function to cast an object to a specific type if it matches the generic type. If the object is null or does not match the type, it returns null.