Sorry in advance if this is already answered (I couldn't find it on SO). We have published a .NET SDK library which exposes one method with generic constraints. My objective is to overload this method and expose another method with different generic constraints.
// This already exists in the SDK.
public T UpdateConfiguration<T>(T entity) where T : ISystemConfig
{
...
}
// This is our objective. Expose another method for users.
public T UpdateConfiguration<T>(T entity) where T : IDataConfig
{
...
}
Apparently, this isn't allowed in C# (.NET 4.7.2).
The compiler raises error: A member UpdateConfiguration<T>(T) is already defined. Rename this member or use different parameter types
.
Coming from a Java background, I was surprised by this error. Although I'm overloading this method, the parameters/arguments are constrained by a different type.
Here are the code samples to show what I mean. This is allowed in Java but disallowed in C#.
- https://ideone.com/7JeprD (Java - works)
- https://ideone.com/fE3pxj (C# - doesn't work)
What's the best way to handle this in terms of best engineering practices? I don't want to rename the method as UpdateConfiguration2
since we want to maintain some uniformity in our SDK for consumers.
As the compiler suggests, is changing the Argument type the only solution?
T UpdateConfiguration(ISystemConfig entity)
& T UpdateConfiguration(IDataConfig entity)
?
The second option will revoke some of the advantages of type inference. Currently, UpdateConfiguration(SomeType obj)
would infer T
as SomeType
. By changing the arguments (second option), I'll have to do UpdateConfiguration<SomeType>(SomeType obj)
every time to infer T
.
Also, any logical reason why this feature isn't supported in C#?