Permit type inference based on default parameters #4035
Unanswered
alx9r
asked this question in
Language Ideas
Replies: 2 comments 8 replies
-
I think I understand the proposal, but I can't think off the top of my head of any time I would have used it. I think it would be help evaluate your proposal if you explained in more detail exactly what your use case is. |
Beta Was this translation helpful? Give feedback.
1 reply
-
If I understand it correctly, the workaround you have today is this: public static void Bar<A>(A a) {}
public static void Bar(int a = 42) => Bar<int>(a); The overloads could be generated by a source generator, so you could just provide a partial declaration, public static void Bar<A>(A a) {}
public static partial void Bar(int a = 42); Since CLR can't represent |
Beta Was this translation helpful? Give feedback.
7 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
tl;dr;
The motivation for this seems close to #1348 and #1349. To my reading permitting this might be moot if those are implemented. It's probably too early to say; there doesn't seem to be a spec for that feature yet.
My stackoverflow question about this has some exploration of where I thought the C# spec applies.
What I am trying to do here
In the example below I am trying to accomplish default type deduction by specifying default parameters in the declaration of a generic method.
Why I am trying to do this
I have some objects that have on the order of 10 generic parameters. The object is a projection of a well-understood and -structured domain into C#. Strongly-typing the parameters prevents use at compile time of those objects in ways that make no sense in the domain.
Most of the parameters have default values that are natural in the domain.
The natural way to specify such an object is to provide an arbitrary subset of the parameters when creating the objects. Default parameters works very well in such a situation because doing so dramatically reduces the number of overloads necessary to support defaults.
I'd like to be able to use default parameters with generic methods to avoid the many overloads that would otherwise be required to handle the omission of an arbitrary combination of parameters. I'd like to be able to do that when those parameters have generic types.
Why I think this should work
My naïve interpretation of the 5.0 spec is that type inference based on default parameters isn't prohibited.
From the example below it seems like the following two calls
should be equivalent.
Example
Expected result:
When
public static void Bar<A>(A a=42) {}
is called using the defaultBar(42)
,Bar<int>(int a)
is inferred.Actual result:
public static void Bar<A>(A a=42) {}
results inBeta Was this translation helpful? Give feedback.
All reactions