Suggestion: Overloading with generics using where clause #3095
Replies: 5 comments 1 reply
-
Generic constraints aren't a part of the method signature in IL, the runtime can't distinguish between them. The runtime would need to be modified to change this, but that would also impact how methods are resolved in IL and require that generic constraints be included in method references. The language couldn't do that much here short of generating mangled names. But that wouldn't work well with other languages in the ecosystem or down-level compilers. |
Beta Was this translation helpful? Give feedback.
-
The type is not clearly defined. You can have any type implement both The methods could actually be differentiated with some |
Beta Was this translation helpful? Give feedback.
-
You can introduce a defaulted parameter with the constraint which solves this in the calling code. using System;
using System.IO;
public interface IBinarySerializable {}
public class Read<T> {}
public class RequireBinarySerializableNew<T>
where T : IBinarySerializable, new()
{}
public static class C
{
// Тут для простоты не добавил.
public static E Read<E>(this BinaryReader reader) where E : struct, System.Enum
{
Console.WriteLine("where E : struct, System.Enum");
return new();
}
public static T Read<T>(this BinaryReader r, RequireBinarySerializableNew<T>? _ignore = null)
where T : IBinarySerializable, new()
{
Console.WriteLine("where T : IBinarySerializable");
return new();
}
}
class ClassBinarySerializable : IBinarySerializable
{
public ClassBinarySerializable() {}
}
enum TestEnum {}
class A{
public static void Main() {
var a = new BinaryReader(new MemoryStream());
a.Read<TestEnum>();
a.Read<ClassBinarySerializable>();
}
} |
Beta Was this translation helpful? Give feedback.
-
Your motivating example is not very compelling. It does not need generics at all. The method implementations are different and you can simply replace T with the concrete type. Problem solved. Would be interesting to see an example where this would actually be useful. |
Beta Was this translation helpful? Give feedback.
-
Hello
I was wondering if it were possible to overload using generics with a where clause.
An example:
The code considers the two signatures to be the same even though the type is clearly defined in the where clause:
Would it not be possible for C# to detect this as an overload?
Beta Was this translation helpful? Give feedback.
All reactions