Search code examples
c#using-directives

On "using" to abbreviate object definitions of generic type


I'm quite new to C# so I apologize if this has been asked before but I've done some searches and haven't found what I'm looking for.

Specifically, I'm aware I can use the keyword using in the following manner to (in some way) mimic the use of typedef:

using myStringDict = System.Collections.Generic.Dictionary<string, string>;

or other pre-defined types.

I am curious to know if there is a way to do this with generic types. As in

using mySomethingDict<T,K> = System.Collections.Generic.Dictionary<T,K>; //this doesn't work

This is all to avoid having to include using System.Collections.Generic; in my files (as there are many files in my project).

Alternative advice is also welcome.


Solution

  • You´re misusing the using-statement. The meaning of this statement depends on its context. In your case you refer to the "using alias directive" to define an alias for a namespace or a type. However this is usually used to avoid ambuigities, e.g. when you have your own class Math defined but want to use the System.Math-class in your code also. So in order to be able to refer to both types, you can use a using as alias, e.g. using MyMath = MyNamespace.Math.

    So using is not the C#-equivalent for a typedef.

    On the other side it´s absolutely okay to have multiple usings in your code, it simply shows the classes that are used by your code. You shouldn´t bother for that at all. In contrast to your statement in your question you´re not importing a complete namespace. You simply load the classes you want to use in your code. You could do the exact same by don´t use any using and allways use fully-qualified names for all the types, e.g. System.Generics.Dictionary. This will compile to the exact same code, but is harder to read and write.

    This difers from how JAVA imports types - which might be the cause for your confusion. In JAVA you can write import MyNameSpace.* to load all classes within the namespace MyNameSpace. In C# however there´s no such thing, you´re just refering to single types.

    See also the examples on the alias