I have a class that I use every time I need to return something in my APIs.
public class OperResult<T>
{
public bool Ok { get; private set; }
public T Data { get; private set; }
// Failed result (Ok: false)
public string ErrorCode { get; private set; }
public string ErrorMessage { get; private set; }
public static OperResult<T> Success(T data)
{
return new OperResult<T>(data);
}
public static OperResult<T> Error(string message, string code = null)
{
return new OperResult<T>(message, code);
}
private OperResult(T data = default(T))
{
Data = data;
Ok = true;
}
private OperResult(string message, string code = null)
{
ErrorCode = code;
ErrorMessage = message;
Ok = false;
}
}
And one that doesn't have generics
public class OperResult
{
public string ErrorCode { get; private set; }
public string ErrorMessage { get; private set; }
public object Data { get; private set; }
public bool Ok { get; private set; }
public static OperResult Success(object data = null)
{
return new OperResult(data);
}
public static OperResult Error(string message, string code = null)
{
return new OperResult(message, code);
}
private OperResult(object data)
{
Data = data;
Ok = true;
}
private OperResult(string message, string code = null)
{
ErrorCode = code;
ErrorMessage = message;
Ok = false;
}
}
In every API response, I return these objects so I know the data and the status of the operation.
public async Task<OperResult<IEnumerable<string>>> GetLocationNames()
{
var locations = await locationService.GetAll(AuthState);
if (location != null)
return OperResult<IEnumerable<string>>.Success(locations.Select(u => u.name));
else
return OperResult<IEnumerable<string>>.Error("No location data found");
}
I would like to be able not to write the Generics part every time I use it. Maybe something like:
public async Task<OperResult<IEnumerable<string>>> GetLocationNames()
{
var locations = await locationService.GetAll(AuthState);
if (location != null)
return OperResult.Success(locations.Select(u => u.name)); // infer <IEnumerable<string>>
else
return OperResult.Error("No location data found"); // here too
}
Is this possible?