简体   繁体   中英

A null object cast to int causes NullReferenceException?

I have the following generic code:

public V put(K key, V value){
        Object o = doOp(ClusterOperation.CONCURRENT_MAP_PUT, key, value);           
        return (V)o;
}

The thing is, the Object o can be null. When I work with objects like String it is ok to return null cast to String. But when V represents int, then null cast to int throws NullReferenceException.

Is there any solution that is generic enough and handles int's?

Thanks

Use the default keyword:

if(o == null)
  return default(V);

return (V)o;

Use int? (ie a nullable int ) instead of int .

int cannot be null as long as it's not an nullable int. If your int can be null it also feels like it's the correct solution to use nullable anyways.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM