简体   繁体   中英

how to pass 2 return types in a method in C#?

I'm in a service method that is supposed to return a user list, but in case it doesn't return this list it is supposed to return a string. I did some research it seems that I have to use a generic the problem is that I have trouble to understand how it works and therefore adapt the synthax to my use case. Thanks for your help.

public async Task<IEnumerable<Utilisateur>> AllUtilisateur(FormUserDTO formUserDTO)
{
 if(user){
   return user //Is a list
 }
 return error // Is a string
}

Maybe try a small wrapper class that encapsulate the result you want

public class AsyncTaskResult<T>
{
    public string Error {get; set;}
    public T Value {get; set;}
    public bool Failed => string.IsNullOrEmpty(Error);
}


public async Task<AsyncTaskResult<IEnumerable<Utilisateur>>> AllUtilisateur(FormUserDTO formUserDTO)
{
 if(user){
   return new AsyncTaskResult<IEnumerable<Utilisateur>>> { Value = user } //Is a list
 }
 return new AsyncTaskResult<IEnumerable<Utilisateur>>> { Error = error } // Is a string
}

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