"Ajeet" <asgrewal@gmail.comwrote in message
news:1169119502.422928.148160@s34g2000cwa.googlegr oups.com...
Quote:
Jon Skeet [C# MVP] wrote:
Quote:
>Ajeet wrote:
Quote:
I am having some difficulty in casting using generics. These are the
classes.
>>
><snip>
>>
Quote:
What do I have to do to be able to cast it as desired? If you can give
me links that describe the solution, I will be grateful (I tried some
googling but to no luck so far).
>>
>You can't. As far as I can tell, your problem is the same one as often
>bites people that you can't cast from List<stringto List<object>.
>That's an easier example to work with, so I'll do so, if you don't mind
>:)
>>
>Suppose C# generics supported covariance in types. I could do:
>List<stringsl = new List<string>();
>List<objectol = sl;
>ol.Add (new object());
>>
>At that point I've clearly broken the idea that the list should only
>contain strings.
>>
>
that makes sense. I did not think of that.
>
Can I overload the cast operator and do this?
Should be possible, although it may be better to make an explicit conversion
function.
Something like:
public interface IProvider<PROF>
where PROF : IProviderProfile
{
private readonly PROF internalProfile;
private IProfile(PROF prov) : internalProvider(prov) {}
//Public constructors
//Some properties/methods
public IProvider<BASEPROFCovary<BASEPROF>() where PROF : BASEPROF
{ return new IProvider<BASEPROF>(internalProfile); } // because
internalProfile casts to BASEPROF
// if IProfile has any internal state, you need to find
a way to share that too,
// possibly via pointer-to-implementation paradigm
// now you also need a generic operator==, not sure if that is possible
}
Quote:
>
Quote:
>Now, it could be that your interfaces wouldn't actually have that
>problem (i.e. there wouldn't be any methods/properties exposed which
>gave rise to the issue), but that's why it's disallowed.
>>
>Are you absolutely sure you need generics here in the first place?
>>
>
We deliberated quite a bit before deciding on generics, so there are
quite a few reasons for doing this. Although I admit we did not foresee
this problem occurring. Do you think there are disadvantages to using
generics?
>
>