views:

69

answers:

2

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.

+1  A: 

Casting it to object before to cast to generic T, should work well:

    if (valueObject is Boolean)
    {
         this.valueObject = (T)(object)((errors == null) || errors.Count == 0);
    }
digEmAll
wow that was a major brain fart on my behalf. Thank you.
Nix
A: 
public Result(List<Error> errors)
{
    valueObject = default(T);
    if (typeof(T) == typeof(bool)) // no need to check the object, we know the generic type
    {
       if (errors == null || errors.Count == 0)
           valueObject = (T)(object)true; // a 'magic' cast to make it compile
    }
    this.errors = errors;
}
VladV