Paul
Paul

Reputation: 620

Working with C# generic method and making it strongly typed

I have two profile types which are:

TeamPlayerPage.cs & TeamStaffMemberPage

In my code (which is an Umbraco solution) I have created two methods that get and build up a collection of profiles e.g.

GetPlayerProfiles(TeamPlayersLandingPage teamPlayersPage)
GetStaffProfiles(TeamStaffLandingPage staffMembersPage)

Within each of the above methods i create a SponsorListItem to associate a sponsor with the profile. Example below

private SponsorListItem GetPlayerSponsor(TeamPlayerPage teamPlayerPage)
{
    if (teamPlayerPage.Sponsor == null)
        return null;

    var sponsorPage = teamPlayerPage.Sponsor as SponsorPage;

    var sponsor = new SponsorListItem()
    {
        Heading = sponsorPage.Heading,
        Url = sponsorPage.Url,
        ListingImgUrl = sponsorPage.Image != null ? sponsorPage.GetCropUrl("image", "360x152(listing)") : Global.PlaceholderImage.GenericListingItem,
        KeySponsor = sponsorPage.KeySponsor
    };

    return sponsor;
}

The sponsor logic is exactly the same for each type so i would like to create one generic method e.g GetProfileSponsor(T profilePage) as opposed to two (see below) The goal is to be able to pass either aa TeamPlayerPage or TeamStaffMemberPage to a generic method and have it be strongly typed so i can access the properties on it.

private SponsorListItem GetPlayerSponsor(TeamPlayerPage teamPlayerPage)
private SponsorListItem GetStaffSponsor(TeamStaffMemberPage staffMembersPage)

I created the following but i'm not quite sure how to make the T profilePage parameter strongly typed against what is passed in (if that is possible)

enter image description here

I have done some searching around but struggling to understand the concept a little. Can someone please point me into the right direction ?

Thank you

Paul

Upvotes: 1

Views: 1197

Answers (1)

DavidG
DavidG

Reputation: 118937

To do this, both of your classes need to implement a common interface so you can constrain the method to that. For example:

public interface ISponsor
{
    SponsorPage Sponsor { get; }
}

And then make your class implement that interface:

public class TeamPlayersLandingPage : ISponsor
{
}

Now you can constrain your generic method:

private SponsorListItem GetProfileSponsor<T>(T profilePage)
    where T : ISponsor
{
    var sponsor = profilePage.Sponsor;
}

Upvotes: 3

Related Questions