This tutorial is about getting different responses in one class using a generic class.
We can implement that by using a generic class. So first, we have to use the namespace.
using System.Collections.Generic
After adding the namespace, we must create a generic class and pass a type parameter in angle brackets after the class name.
public class Response < T > {
public HttpStatusCode ResponseCode {
get;
set;
}
public string ResponseMessage {
get;
set;
}
public string ResponseDesc {
get;
set;
}
public bool IsSuccess {
get;
set;
}
public T Result {
get;
set;
}
public Response() {
this.ResponseCode = HttpStatusCode.OK;
this.ResponseMessage = ResponseCommon.GetEnumName(HttpStatusCode.OK);
this.ResponseDesc = ResponseCommon.GetEnumName(ResultDescription.Success);
this.IsSuccess = true;
}
}
We can use that class just by passing the parameter data type. For example, I created a class Response<T>, then we have to pass just like this Response<int>, Response<string>, and Response<AnyClass>
The following shows how to use Response<T> in the WebAPI or any other method. You can see the below snippet.
public Response < List < User >> GetUserList() {
Response < List < Users >> ResponseFinal = new Response < List < Users >> ();
List < Users > UsersList = new List < Users > ();
try {
UsersList = new DAL_User().GetUserList();
if (UsersList.Count > 0) {
ResponseFinal.Result = UsersList;
} else {
ResponseFinal.IsSuccess = false;
ResponseFinal.ResponseCode = HttpStatusCode.BadRequest;
ResponseFinal.ResponseMessage = ResponseCommon.GetEnumName(ResultDescription.Failed);
ResponseFinal.ResponseDesc = ResponseCommon.GetEnumName(ResultDescription.Failed);
ResponseFinal.Result = UsersList;
}
} catch (Exception ex) {
ResponseFinal.IsSuccess = false;
ResponseFinal.ResponseCode = HttpStatusCode.ExpectationFailed;
ResponseFinal.ResponseMessage = ResponseCommon.GetEnumName(ResultDescription.Exception_Found);
ResponseFinal.ResponseDesc = ex.Message;
ResponseFinal.Result = UsersList;
}
return ResponseFinal;
}