Generic cast type to primitive.
Posted
by Nix
on Stack Overflow
See other posts from Stack Overflow
or by Nix
Published on 2010-04-28T13:03:50Z
Indexed on
2010/04/28
13:13 UTC
Read the original article
Hit count: 265
Is there a way to do the below? Imagine a generic result wrapper class. Where you have a type and an associated error list. When there is no result to return to the user we will use boolean to indicate success failure. I want to create a constructor that takes in an error list, and if the list is null or count 0, AND the type is a bool/Boolean i want to set it to true....
Seemingly simple, but amazingly not possible.
public class Result<T>{
private T valueObject { get;set;}
private List<Error> errors{ get;set;}
public Result(T valueObj, List<Error> errorList){
this.valueObject = valueObj;
this.errors = errorList;
}
public Result(List<Error> errors)
{
this.valueObject = default(ReturnType);
if (valueObject is Boolean)
{
//Wont work compile
//(valueObject as Boolean) = ((errors == null) || errors.Count == 0);
//Compiles but detaches reference
//bool temp = ((bool)(valueObject as object)) ;
//temp = ((errors == null) || errors.Count == 0);
}
this.errors = errors;
}
}
}
Am I missing something simple? And in general I would prefer to do it without reflection.
© Stack Overflow or respective owner