[Solved] Why this is not possible in C#? [closed]


Looks like an interesting case on what is allowed as a generic parameter type name.
This:

class DoesSomething<T> : IDoSomething<string>
{
    public void Dispose()
    {
    }
}

and this

class DoesSomething<T> : IDoSomething<String>
{
    public void Dispose()
    {
    }
}

is obvious. Here T is used as a generic parameter name.

On the other hand this

class DoesSomething<string> : IDoSomething<string>
{
    public void Dispose()
    {
    }
}

doesn’t make much sense, since it tries to introduce a concrete type (string) as a parameter name where only fresh names are allowed.

What is only interesting here is that it actually works where a generic parameter type name collides with an existing type name. Looks like the compiler allows that but of course gives different meaning to both Strings.

public interface IDoSomething<in TSource> : IDisposable { }

class DoesSomething<String> : IDoSomething<String>
{
    public void Dispose()
    {
    }
}

public class Program
{
    public static void Main()
    {
        DoesSomething<int> _ = new DoesSomething<int>();
    }
}

The String in IDoSomething<String> is bound to TSource in the interface definition.

The String in DoesSomething<String> introduces a type parameter which is then expected to be provided by the client (int in the example above).

6

solved Why this is not possible in C#? [closed]