Namespace scoped aliases for generic types in C#
Posted
by TN
on Stack Overflow
See other posts from Stack Overflow
or by TN
Published on 2010-04-07T07:23:31Z
Indexed on
2010/04/07
8:13 UTC
Read the original article
Hit count: 205
Let's have a following example:
public class X { }
public class Y { }
public class Z { }
public delegate IDictionary<Y, IList<Z>> Bar(IList<X> x, int i);
public interface IFoo
{
// ...
Bar Bar { get; }
}
public class Foo : IFoo
{
// ...
public Bar Bar
{
get
{
return null; //...
}
}
}
void Main()
{
IFoo foo; //= ...
IEnumerable<IList<X>> source; //= ...
var results = source.Select(foo.Bar);
}
The compiler says:
The type arguments for method 'System.Linq.Enumerable.Select(System.Collections.Generic.IEnumerable, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
It's because, it cannot convert Bar
to Func<IList<X>, int, IDictionary<Y, IList<Z>>>
.
It would be great if I could create type namespace scoped type aliases for generic types in C#. Then I would define Bar
not as a delegate, but rather I would define it as an namespace scoped alias for Func<IList<X>, int, IDictionary<Y, IList<Z>>>
.
public alias Bar = Func<IList<X>, int, IDictionary<Y, IList<Z>>>;
I could then also define namespace scoped alias for e.g. IDictionary<Y, IList<Z>>
.
And if used appropriately:), it will make the code more readable. Now I have inline the generic types and the real code is not well readable:(
Have you find the same trouble:)? Is there any good reason why it is not in C# 3.0? Or there is no good reason, it's just matter of money and/or time?
EDIT: I know that I can use using
, but it is not namespace based - not so convenient for my case.
© Stack Overflow or respective owner