Reputation: 4107
In c#, how would I go about setting up a class that can return another class (of any type).
For example:
public class DataResponse {
public bool Success {get;set;}
public string ResponseMessage {get;set;}
public T Data {get;set;}
}
T should be any type of class.
var personData = new PersonClass() {
FirstName= "John",
LastName="Doe"
};
var response = new DataResponse<EmployeeClass>() {
Success = true;
ResponseMessage = "OK";
Data = personData
}
then I can go and get
response.Data.FirstName
The data proprety will be of a changing class it could be a person or an employer for example.
Any help would be appreciated.
Upvotes: 0
Views: 434
Reputation: 1
Make your class generic, as suggested by Sergey Berezovskiy and p.s.w.g. Additionally, you could require that T be of a type that implements FirstName and LastName:
public interface INamable
{
string FirstName { get; set; }
string LastName { get; set; }
}
public class DataReponse<T> where T : INamable
{
public bool Success { get; set; }
public string ResponseMessage { get; set; }
public T Data { get; set; }
}
Upvotes: 0
Reputation: 236318
Make your class generic:
public class DataResponse<T> // class is parametrized with T
{
public bool Success {get;set;}
public string ResponseMessage {get;set;}
public T Data {get;set;}
}
Now your code will work - create class parametrized with some specific type and Data
property will have that type:
var response = new DataResponse<EmployeeClass> {
Success = true;
ResponseMessage = "OK";
Data = personData
};
NOTE: I like to create extension methods which create response objects based on data I have:
public static DataResponse<T> ToSuccessResult<T>(this T data)
{
return new DataResponse<T> {
Success = true;
ResponseMessage = "OK";
Data = data
};
}
Now type of T
can be inferred from your data type and response creation will look like:
var response = personData.ToSuccessResult();
Upvotes: 6
Reputation: 613451
Only methods and types can be generic. Which means that you cannot declare a generic property. The best you can do is make the class that contains the property generic.
public class DataResponse<T>
{
public T Data { get; set; }
}
Upvotes: 2
Reputation: 149050
You need to declare the generic type parameter at the class level:
public class DataResponse<T> // <-- here
{
public bool Success {get;set;}
public string ResponseMessage {get;set;}
public T Data {get;set;}
}
So now, as long as EmployeeClass
has a property named FirstName
, this will work:
var personData = new PersonClass() {
FirstName = "John",
LastName = "Doe"
};
var response = new DataResponse<EmployeeClass>() {
Success = true;
ResponseMessage = "OK";
Data = personData
};
Console.WriteLine(response.Data.FirstName); // John
Upvotes: 3