Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# public class where T : class, Class, new() confusion

I am new to C# and I am faced with a class with this structure:

public class SimpleGetter<TSubs> : GetterBase<TSubs>, ISubscriptionsSingleGetter<TSubs>
    where TSubs : class, ISimpleSubscription, new()
{
    UserSubscriptionsResponse<TSubs> ISubscriptionsSingleGetter<TSubs>.Get()
    {
        return ((ISubscriptionsSingleGetter<TSubs>)this).Get(null);
    }

    UserSubscriptionsResponse<TSubs> ISubscriptionsSingleGetter<TSubs>.Get(string userId)
    {
        return GetSubsResponse(userId);
    }
}

I need to pass userID to the get() function (if possible), but I am confused on how to do that. I have tried to do some research on this but I do not even know what this way of defining a class is called. I come from objective c where things seem more straight forward.

like image 357
pnizzle Avatar asked Dec 04 '22 00:12

pnizzle


1 Answers

I do not even know what this way of defining a class is called

This is a generic class.

  public class SimpleGetter<TSubs> : GetterBase<TSubs>, ISubscriptionsSingleGetter<TSubs>
    where TSubs : class, ISimpleSubscription, new()

which has one generic type parameter TSubs. This class inherits the GetterBase<TSubs> and implements the interface ISubscriptionsSingleGetter<TSubs>. Furthermore, the TSubs must be a reference type and must have a parameterless constructor, which implements the ISimpleSubscription interface.

public class FakeSubs : ISimpleSubscription
{
    public FakeSubs()
    {

    }

    // Here you have to implement ISimpleSubscription. 
    // You could also define any properties, methods etc.
}

// Now you could use your generic class as below:

var simpleGetter = new SimpleGetter<FakeSubs>();

Having created the above instance, you can call the Get method as Tewr, pointed out in his comment:

var response = ((ISubscriptionsSingleGetter<FakeSubs>)simpleGetter).Get(42);
like image 132
Christos Avatar answered Dec 18 '22 16:12

Christos