view raw
iLoveUnicorns iLoveUnicorns - 10 months ago 50
Java Question

c# Model abstraction and generics, cast unknown generic like Java

Basic Java way

class SomeModelController {

public void makeSomeRequest<T extends BaseJsonClass>(Type type, RequestCallback requestCallback) {
// Do request stuff.

// Some code
ModelController.makeRequest<UserLoginResponse>(UserLoginResponse.class, new RequestCallback() {
public void success(UserLoginResponse sucessObject) {
// Object is now treated like response.

I'm aware that C# does not have a type erasor; so I can just use T (Generic as is?)
My C# class and where I'm struggling:

public class Response<T> {

private Action<T> success;
private Action<FailedReason> failed;

public Response(Action<T> success, Action<FailedReason> failed) {
this.success = success;
this.failed = failed;

public void Success<T>(T objectSuccess) {
// ?? How to convert success object to type?

public void Failed(FailedReason failedReason) {


Edit 1
I'm getting the following complaint from the compiler:

I'm getting "Cannot implicitly convert T to T"
when trying to compile.


You can simply call

public void Success(T objectSuccess) {

objectSuccess is of type T. That's exactly what Action<T> success expects as parameter. No conversion is required.

You can think of success as being a method declared like this:

void success(T arg)

And as Jorn Vernee says, remove <T> from Success<T>. You don't need a generic type parameter for this method, as it uses the generic type parameter of the class. If for some reason you need different generic type parameters for class and method, you must give them different names. But that's not the case here.