Nerf
Nerf

Reputation: 938

Implicit cast array

I have two classes that are atm that same and defined cast:

 public static implicit operator SponsoredBrandViewModel(SponsoredBrand sponsoredBrand)
        =>
            new SponsoredBrandViewModel
            {
                Id = sponsoredBrand.Id,
                BrandId = sponsoredBrand.RelatedEntityId,
                To = sponsoredBrand.To,
                From = sponsoredBrand.From,
                Importance = sponsoredBrand.Importance
            };
    public static implicit operator SponsoredBrand(SponsoredBrandViewModel sponsoredBrandViewModel)
        =>
            new SponsoredBrand
            {
                Id = sponsoredBrandViewModel.Id,
                RelatedEntityId = sponsoredBrandViewModel.BrandId,
                To = sponsoredBrandViewModel.To,
                From = sponsoredBrandViewModel.From,
                Importance = sponsoredBrandViewModel.Importance
            };

I want to make it cast when it's a array.

ar dbSponsoredBrands = await this._sponsoredBrandRepository.GetAsync();
            var viewModels = (IEnumerable<SponsoredBrandViewModel>) dbSponsoredBrands.ToEnumerable();

But this throwing invalidcast exception.

Any ideas?

Upvotes: 2

Views: 334

Answers (2)

ChriPf
ChriPf

Reputation: 2780

You can use the LINQ-Functions

.Cast<SponsoredBrandViewModel>()

or

.OfType<SponsoredBrandViewModel>()

to achieve that. These will iterate over the result too, but in a lazy way. Use the first one if you are sure every element is of this type, the later one if you want to filter only the matching elements.

Upvotes: 0

Chris Pickford
Chris Pickford

Reputation: 8991

You're trying to cast the collection object IEnumerable<SponsoredBrand> into an IEnumerable<SponsoredBrandViewModel> where you've defined your implicit cast operator for the actual object. You'll need to iterate through the collection and create a new one, e.g.

var dbSponsoredBrands = await this._sponsoredBrandRepository.GetAsync();
var viewModels = dbSponsoredBrands.Select(x => (SponsoredBrandViewModel)x);

Upvotes: 2

Related Questions