HighTechTalks DotNet Forums  

C# generics: wildcards

Dotnet Framework (SDK) microsoft.public.dotnet.framework.sdk


Discuss C# generics: wildcards in the Dotnet Framework (SDK) forum.



Reply
 
Thread Tools Search this Thread Display Modes
  #1  
Old   
Puce
 
Posts: n/a

Default C# generics: wildcards - 03-07-2006 , 10:56 AM






Hi,

I've got the following classes and interfaces:

public interface ICommand<T> where T : IResult
{
T Process();
}

----

interface IResult...

----

class AuthenticationResult : IResult...

----

class AuthenticationCommand : ICommand<AuthenticationResult>{

AuthenticationResult Process(){...}
}

-----

With Java I could now do something like the following somewhere in my program:

ICommand<?> command = new AuthenticationCommand();
IResult result = command.Process();

But C# does not know wildcards. Is there a work-around without using casts?

Thanks!

-Puce


Reply With Quote
  #2  
Old   
Helge Jensen
 
Posts: n/a

Default Re: C# generics: wildcards - 03-07-2006 , 12:42 PM








Puce wrote:

Quote:
With Java I could now do something like the following somewhere in my program:

ICommand<?> command = new AuthenticationCommand();
IResult result = command.Process();

But C# does not know wildcards. Is there a work-around without using casts?
In C#3:

var command = new AuthenticationCommand();
IResult result = command.Process();

Which would assign the type "AuthenticationCommand" to command -- not
exactly wildcarding but syntactically similar in this case. In C#2 you
have lost with your exact code.

You can use the explicit type in the declaration of command:

ICommand<AuthenticationResult> command = new AuthenticationCommand();

You might consider making ICommand unparametrised:

interface ICommand { IResult Process(); }

if you really need to uniformly treat results.


An alternative approach, which I don't really like too much is:

interface IResult { }
interface ICommand { IResult Process(); }
interface ICommand<T>: ICommand where T: IResult { new T Process(); }
class Foo: IResult {}
class X : ICommand<Foo> {
IResult ICommand.Process() { return Process(); }
public Foo Process() { return new Foo(); }
}
class Program
{
static void Main(string[] args)
{
ICommand command = new X();
IResult r = command.Process();
}
}


--
Helge Jensen
mailto:helge.jensen (AT) slog (DOT) dk
sip:helge.jensen (AT) slog (DOT) dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-


Reply With Quote
Reply




Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off



Powered by vBulletin Version 3.5.4
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.