The general type of cast to primitive

Is there any way to do this below? Imagine a general result wrapper class. Where do you have the type and its associated error list. When the result is not returned to the user, we will use a boolean to indicate failure success. I want to create a constructor that accepts a list of errors, and if the list is null or count 0 and the type is bool / Boolean, I want to set it to true ....

It seems simple but surprisingly impossible.

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? In general, I would prefer to do this without thinking.

+4
source share
2 answers

Dropping an object before using it to generate T should work well:

  if (valueObject is Boolean) { this.valueObject = (T)(object)((errors == null) || errors.Count == 0); } 
+6
source
 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; } 
0
source

Source: https://habr.com/ru/post/1308238/


All Articles