Can a method be declared with a parameterized return type?

  • Thread starter Thread starter Brad Wood
  • Start date Start date
B

Brad Wood

It doesn't look like something like this is possible in 2.0:
public <T> doStuff();

Am I correct, and if so, there's probably a good reason that I can't
think of why not...
 
You can write a generic method whose return type is its generic type
parameter, but just like all generic definitions, the angle brackets
and type parameters come after the name:

public T DoStuff<T>()
{
...
}

Is that what you're looking for?

Jesse
 
That is what I'm looking for, but attempting a trivial sample is giving
unexpected results.

I would expect the following console app to print "bobo". Instead I get
some crazy type info:

public delegate T AnonymousWithReturn<T>();

static void Main( string[] args )
{
AnonymousWithReturn<string> test = delegate() { return "bobo"; };
Console.WriteLine( test );
Console.ReadLine();
}
 
In your example you haven't executed the delegate; just replace with

Console.WriteLine(test());

and you will be sorted

Marc

Brad Wood said:
That is what I'm looking for, but attempting a trivial sample is giving
unexpected results.

I would expect the following console app to print "bobo". Instead I get
some crazy type info:

public delegate T AnonymousWithReturn<T>();

static void Main( string[] args )
{
AnonymousWithReturn<string> test = delegate() { return "bobo"; };
Console.WriteLine( test );
Console.ReadLine();
}


You can write a generic method whose return type is its generic type
parameter, but just like all generic definitions, the angle brackets
and type parameters come after the name:

public T DoStuff<T>()
{
...
}

Is that what you're looking for?
 
Brad,
As the other have shown you can define a method with a parameterized return
type.

Yes you can define a generic function where the parameter is only used for
the return type.

public T doSomething<T where T:new()>()

However! You need to supply the type parameter when you call the method
directly, something like:

object o = doSomething<object>();
MemoryStream m = doSomething<MemoryStream>();

However! it "violates" an FxCop rule as its "ambiguous".

Here is a thread that discusses it:

http://groups.google.com/group/micr...bb32de857b1/cf4e46ca8f99b798#cf4e46ca8f99b798

Personally I find in the case of GetCustomAttribute (as the thread shows) it
makes sense as the type parameter is encapsulating the downcast, plus the
type parameter is used to "do work".

--
Hope this helps
Jay [MVP - Outlook]
..NET Application Architect, Enthusiast, & Evangelist
T.S. Bradley - http://www.tsbradley.net


| It doesn't look like something like this is possible in 2.0:
| public <T> doStuff();
|
| Am I correct, and if so, there's probably a good reason that I can't
| think of why not...
 
Back
Top