Widening of parameter types for delegates #4249
Replies: 2 comments 3 replies
-
As much as I'd also like an implicit generalization from type In general, I guess it might work to always infer |
Beta Was this translation helpful? Give feedback.
-
Your question is a little bit confused: If you're asking why you can't do... public void Foo(IEnumerable<int?> input) { ... }
Action<IEnumerable<int>> d = Foo; The answer here isn't particularly related to delegates. The problem is that a So (regardless of delegates), there's no straightforward conversion from an The compiler isn't going to generate code which iterates over your If you start looking at reference conversions however, e.g. from Human to Creature to string to object, this is supported by the compiler and has been since C# 4. You don't need to allocate extra storage here, as all references are the same size. This compiles and works perfectly fine: using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
var strings = new List<string>() { "a", "b", "c" };
var objects = strings.Select(ObjectToString);
Console.WriteLine(string.Join(" ", objects));
}
public static string ObjectToString(object foo) => foo.ToString();
} https://dotnetfiddle.net/wpezn2 If you're asking why you can't do: public void Foo(int? x) { }
Action<int> d = Foo; The answer here is similar: If you simply write If however you write public void Foo(int? x) { }
public void CompilerGeneratedMethod(int x) => Foo(new Nullable<int>(x));
Action<int> d = CompilerGeneratedMethod; Here, there's no promise that the delegate's |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
If I have a method like so:
And then I want to pass that method as a delegate to another method, say, a LINQ query, but with a more specific parameter type:
Then I get a compile error because
nums
has a type parameter ofint
whileNumbersToStrings
has a type parameter ofint?
.But there is an implicit widening conversion from
int
toint?
. So this should not cause an error. Same for conversions from smaller numeric types to larger ones (e.g.int
tolong
), or from derived types to base classes or interfaces (e.g.Human
toCreature
, orstring
toobject
, orCat
toIFurryThing
).There is a workaround of course; just use a lambda expression:
It would be nice though to not have to do that; is there any reason the types have to match exactly?
Beta Was this translation helpful? Give feedback.
All reactions