473,618 Members | 3,170 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Complex Casting problem in Generics

hi

I am having some difficulty in casting using generics. These are the
classes.

public interface IProvider<PROF>
where PROF : IProviderProfil e
{
//Some properties/methods
}

public interface IAuthentication Provider<PROF, TOK, CRED:
IProvider<PROF>
where PROF : IAuthentication ProviderProfile
where TOK : IToken
where CRED : ICredential
{
//Some methods.
}

public class ADAMAuthenticat ionProvider :
IAuthentication Provider<ADAMAu thenticationPro viderProfile,
ADAMUserToken, UsernamePasswor dCredential>
{
}

The first two are interfaces. The third class is the concrete provider.
My problem is that I cannot cast an instance of
ADAMAuthenticat ionProvider to IProvider<IProv iderProfile>.

I should note here that ADAMAuthenticat ionProviderProf ile derives from
IAuthentication ProviderProfile which derives from IProviderProfil e.
Similarly the token and credential concrete classes are derived from
the interfaces mentioned in the constraints in the 2nd interface.

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).

Regards,
Ajeet.

Jan 18 '07 #1
7 2200
Ajeet wrote:
I am having some difficulty in casting using generics. These are the
classes.
<snip>
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.

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?

Jon

Jan 18 '07 #2
Jon Skeet [C# MVP] wrote:
Ajeet wrote:
I am having some difficulty in casting using generics. These are the
classes.

<snip>
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?
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?
Jon
Jan 18 '07 #3

"Ajeet" <as******@gmail .comwrote in message
news:11******** **************@ s34g2000cwa.goo glegroups.com.. .
Jon Skeet [C# MVP] wrote:
>Ajeet wrote:
I am having some difficulty in casting using generics. These are the
classes.

<snip>
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<strings l = new List<string>();
List<objecto l = 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 : IProviderProfil e
{
private readonly PROF internalProfile ;
private IProfile(PROF prov) : internalProvide r(prov) {}
//Public constructors
//Some properties/methods
public IProvider<BASEP ROFCovary<BASEP ROF>() where PROF : BASEPROF
{ return new IProvider<BASEP ROF>(internalPr ofile); } // 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
}

>
>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?
>Jon

Jan 18 '07 #4
Hi Ajeet,

a solution could be, to have a non generic Interface IProvider from wich
IProvider<deriv es.
Then you could cast to this Interface instead of casting to
IProvider<IProv iderProfile>

public interface IProvider<PROF: IProvider where PROF : IProviderProfil e
{
}

Would this help you?

"Ajeet" <as******@gmail .comschrieb im Newsbeitrag
news:11******** **************@ s34g2000cwa.goo glegroups.com.. .
hi

I am having some difficulty in casting using generics. These are the
classes.

public interface IProvider<PROF>
where PROF : IProviderProfil e
{
//Some properties/methods
}

public interface IAuthentication Provider<PROF, TOK, CRED:
IProvider<PROF>
where PROF : IAuthentication ProviderProfile
where TOK : IToken
where CRED : ICredential
{
//Some methods.
}

public class ADAMAuthenticat ionProvider :
IAuthentication Provider<ADAMAu thenticationPro viderProfile,
ADAMUserToken, UsernamePasswor dCredential>
{
}

The first two are interfaces. The third class is the concrete provider.
My problem is that I cannot cast an instance of
ADAMAuthenticat ionProvider to IProvider<IProv iderProfile>.

I should note here that ADAMAuthenticat ionProviderProf ile derives from
IAuthentication ProviderProfile which derives from IProviderProfil e.
Similarly the token and credential concrete classes are derived from
the interfaces mentioned in the constraints in the 2nd interface.

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).

Regards,
Ajeet.

Jan 18 '07 #5

Ben Voigt wrote:
"Ajeet" <as******@gmail .comwrote in message
news:11******** **************@ s34g2000cwa.goo glegroups.com.. .
Jon Skeet [C# MVP] wrote:
Ajeet wrote:
I am having some difficulty in casting using generics. These are the
classes.

<snip>

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 : IProviderProfil e
{
private readonly PROF internalProfile ;
private IProfile(PROF prov) : internalProvide r(prov) {}
//Public constructors
//Some properties/methods
public IProvider<BASEP ROFCovary<BASEP ROF>() where PROF : BASEPROF
{ return new IProvider<BASEP ROF>(internalPr ofile); } // 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
}
yeah .. i thought more about the explicit casting approach. There are
other drawbacks. The principal one that I see is that there will be no
runtime polymorphism anymore. Plus, if I later want to cast it back to
the original type, that would prove impossible.

Do you guys have any solution that will address these problems?

I am currently calling the methods through reflection. This makes all
the interfaces pretty much useless. I don't see a good solution to the
problem though.
>
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?
Jon
Jan 19 '07 #6

Christof Nordiek wrote:
Hi Ajeet,

a solution could be, to have a non generic Interface IProvider from wich
IProvider<deriv es.
Then you could cast to this Interface instead of casting to
IProvider<IProv iderProfile>

public interface IProvider<PROF: IProvider where PROF : IProviderProfil e
{
}

Would this help you?
No this would be of no use. I need to cast into that interface because
that interface contains some methods that I need to call. Doing this
would leave me with an empty interface which I will not be able to use.
"Ajeet" <as******@gmail .comschrieb im Newsbeitrag
news:11******** **************@ s34g2000cwa.goo glegroups.com.. .
hi

I am having some difficulty in casting using generics. These are the
classes.

public interface IProvider<PROF>
where PROF : IProviderProfil e
{
//Some properties/methods
}

public interface IAuthentication Provider<PROF, TOK, CRED:
IProvider<PROF>
where PROF : IAuthentication ProviderProfile
where TOK : IToken
where CRED : ICredential
{
//Some methods.
}

public class ADAMAuthenticat ionProvider :
IAuthentication Provider<ADAMAu thenticationPro viderProfile,
ADAMUserToken, UsernamePasswor dCredential>
{
}

The first two are interfaces. The third class is the concrete provider.
My problem is that I cannot cast an instance of
ADAMAuthenticat ionProvider to IProvider<IProv iderProfile>.

I should note here that ADAMAuthenticat ionProviderProf ile derives from
IAuthentication ProviderProfile which derives from IProviderProfil e.
Similarly the token and credential concrete classes are derived from
the interfaces mentioned in the constraints in the 2nd interface.

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).

Regards,
Ajeet.
Jan 19 '07 #7
"Ajeet" <as******@gmail .comschrieb im Newsbeitrag
news:11******** **************@ l53g2000cwa.goo glegroups.com.. .
>
Christof Nordiek wrote:
>Hi Ajeet,

a solution could be, to have a non generic Interface IProvider from wich
IProvider<deri ves.
Then you could cast to this Interface instead of casting to
IProvider<IPro viderProfile>

public interface IProvider<PROF: IProvider where PROF :
IProviderProfi le
{
}

Would this help you?

No this would be of no use. I need to cast into that interface because
that interface contains some methods that I need to call. Doing this
would leave me with an empty interface which I will not be able to use.
You can cast to the IProvider interface. Give the IProvider interface all
methods you will need in the general case. The implement them either
implicitly or explicitly by calling the resp. method with typeparameter as
return type.

public interface IProvider
{
IProviderProfil e GetProfile();
void OtherMethod();
}

public interface IProvider<PROF> : IProvider where PROF : IProviderProfil e
{
PROF GetProfile();
}

public class MyProvider : IProvider<MyPro file>
{
public IProviderProfil e GetProfile()
{
implementation goes here.
}

IProvider.GetPr ofile() { return GetProfile(); }

public OtherMethod()
{
some other impl. here
}
}

will this work for you?
>"Ajeet" <as******@gmail .comschrieb im Newsbeitrag
news:11******* *************** @s34g2000cwa.go oglegroups.com. ..
hi

I am having some difficulty in casting using generics. These are the
classes.

public interface IProvider<PROF>
where PROF : IProviderProfil e
{
//Some properties/methods
}

public interface IAuthentication Provider<PROF, TOK, CRED:
IProvider<PROF>
where PROF : IAuthentication ProviderProfile
where TOK : IToken
where CRED : ICredential
{
//Some methods.
}

public class ADAMAuthenticat ionProvider :
IAuthentication Provider<ADAMAu thenticationPro viderProfile,
ADAMUserToken, UsernamePasswor dCredential>
{
}

The first two are interfaces. The third class is the concrete provider.
My problem is that I cannot cast an instance of
ADAMAuthenticat ionProvider to IProvider<IProv iderProfile>.

I should note here that ADAMAuthenticat ionProviderProf ile derives from
IAuthentication ProviderProfile which derives from IProviderProfil e.
Similarly the token and credential concrete classes are derived from
the interfaces mentioned in the constraints in the 2nd interface.

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).

Regards,
Ajeet.

Jan 19 '07 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
1688
by: c | last post by:
Hello All, I am struggling with simple casting issue within c# and would really appreciate some insight into where I am going wrong. I have two classes, ClassA and ClassB. Each implements a "public static implicit operator" to allow silent casting from one to the other. This works fine, per the documents I have read. However, I am unable to do this:
7
3661
by: yufufi | last post by:
lets say we have a 'shape' class which doesn't implement IComparable interface.. compiler doesn't give you error for the lines below.. shape b= new shape(); IComparable h; h=(IComparable)b; but it complains for the following lines
4
25403
by: KC | last post by:
Could some one explain to me the casting rules for sending generic lists, ex. List<Person>, to a function that accepts List<object>? I cannot get the following easy-cheesy app to work. I get the following error: Argument '1': cannot convert from 'GenericsPOC.ArticleCollection' to 'System.Collections.Generic.IList<object>' I tried casting specifically to IList<object> but then I get a runtime error: Unable to cast object of type...
4
2565
by: krahenbuhl | last post by:
Dear All, I've a question related to Generics and casting in c# 2.0. I've a class called Client which implements interface IClient. I'd like to do: LinkedList<Client> clients; public LinkedList<IClient> getClients() { return clients;
5
2916
by: anders.forsgren | last post by:
This is a common problem with generics, but I hope someone has found the best way of solving it. I have these classes: "Fruit" which is a baseclass, and "Apple" which is derived. Further I have an "AppleBasket" which is a class that contains a collection of apples. So, some code: class Fruit{ }
8
2412
by: Kris Jennings | last post by:
Hi, I am trying to create a new generic class and am having trouble casting a generic type to a specific type. For example, public class MyClass<Twhere T : MyItemClass, new() { public MyClass() { } public void AppendItem()
3
2755
by: Tigger | last post by:
I have an object which could be compared to a DataTable/List which I am trying to genericify. I've spent about a day so far in refactoring and in the process gone through some hoops and hit some dead ends. I'm posting this to get some feedback on wether I'm going in the right direction, and at the same time hopefully save others from going through the process.
3
1805
by: psyCK0 | last post by:
Hi all! I have a problem of casting generics to their base type. In the code below I first define a BaseList class that can hold items of any type that inherits from BaseItem. I then define a DerivedList that can hold items of the type DerivedItem, which inherits from BaseList. So far so good... But if I somehow get an object that I know is a subclass of BaseList (and therefor holds subclasses of BaseItem) and try to cast it to...
3
5995
by: =?Utf-8?B?TWlydHVs?= | last post by:
Hi I'm currently working with vbscripting through MSScriptControl. We have shared some of our objects that should be available for scripting. Some of the functions of these objects will return an interface to a class that must be cast to the appropriate higher level class to use all functionality. Thus I tried to implement a generic cast function for use from the vbscript
0
8207
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8650
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8593
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8303
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8453
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7124
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5552
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4147
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1455
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.