How to know what "actual type" of VariationContent I will get?

Vote:
 

Hi,

When I have a variation Code and I want to retrieve its Content, I do this:


var ref = GetCatalogEntryReferenceFromEpi(variationCode);
var content = _contentLoader.Get<VariationContent>(ref, LanguageSelector.AutoDetect(true));

...

This works... but, I'd don't really want type VariationContent.  I want a derived type such as ShirtVariationContent, SneakerVariationContent, etc... But I don't know what type it will be -- because I only have the Code...

What is the recommended way to "know" & get the actual derived type from IContentLoader?

#203378
Apr 18, 2019 21:54
Vote:
 

Hi,

In that case you can use follwoing approach, use TryGet (in below example, here this._contentRepository is instance of IContentRepository)

this._contentRepository.TryGet(contentLink, out content);

And, then do a type check as

if (content is ShirtVariationContent shirtVariationContent)
{
    //// Your code...
}

It will cast your object is condition is true.

Thanks & Regards

/Praful Jangid

#203379
Apr 19, 2019 4:30
Vote:
 

Hi Ken

You can load, cast and check the variation in one line, like this:

if (!_contentLoader.TryGet(contentLink, out SneakerVariationContent sneakerVariation))
{
    // The target does not exist, or the content is not of type 'SneakerVariationContent'. 
    return null;
}

// Do something with the sneakerVariation variable.

You can also put this in a generic method with a type parameter, TContent, by replacing SneakerVariationContent with TContent (but TContent must inherit from IContentData).

#203384
Apr 19, 2019 13:23