1

For example in my code I want the alias MyUser for Dictionary<string,string>

I tried

Type MyUser =typeof(Dictionnary<string,string>);
MyUser user;

But it does not work.

Thank you for your attention.

Fildor
  • 14,510
  • 4
  • 35
  • 67
  • 1
    You can inherit a new type: `public class MyUser : Dictionary{}` – René Vogt Aug 18 '23 at 08:27
  • 2
    [Using directive](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-directive#using-alias) – Nikola Markovinović Aug 18 '23 at 08:28
  • @NikolaMarkovinović that does not help, using aliases can only be used for namespaces, not for specific types. – René Vogt Aug 18 '23 at 08:29
  • 1
    @RenéVogt I disagree. – Nikola Markovinović Aug 18 '23 at 08:30
  • @RenéVogt Pretty sure they added this feature recently. – DavidG Aug 18 '23 at 08:30
  • As to why this _did not work_: Your snippet declares a **variable** `MyUser` of type `Type` and assigned the type information represented as `Type` of `Dictionary`. `MyUser` itself _is not_ declared a type using this syntax. – Fildor Aug 18 '23 at 08:39
  • 1
    @RenéVogt Example: https://dotnetfiddle.net/TEYt31 – DavidG Aug 18 '23 at 08:40
  • besides that, consider that what you are doing might be a bad practice. derriving from Dictionary for MyUser without any _User_ type will give you a collection where _Key_ is ... maybe the Username?? and _Value_ is .?? ... its not beautiful – Michael Schönbauer Aug 18 '23 at 08:41
  • @RenéVogt Thank you! Great! I forgot the possibility of inheritance ... – Jean-Pierre R Aug 18 '23 at 08:42
  • @MichaelSchönbauer The same argument can be made for aliasing, not only for inheritance. But yes, I'd agree to rather use composition over any of the two if no _good_ reasons exist not to in this case. I think the question to ask is: Is this _really_ just some sort of abbreviation or is this supposed to be an abstraction? Latter case _seems_ to apply and that would also be a counter-indication for the usage of an alias. – Fildor Aug 18 '23 at 08:45
  • 1
    @Fildor yes it can be applied to both methods, because both would be considered bad practice in my opinion.. derriving maybe even more than aliasing. – Michael Schönbauer Aug 18 '23 at 08:49
  • @RenéVogt that's just not so. `using MyAlias = SomeType;` has always worked. – Aluan Haddad Aug 18 '23 at 10:16
  • @Charlieface Yes, this fully meets my request. Thx – Jean-Pierre R Aug 21 '23 at 11:37

3 Answers3

5

Since C# 10 you have been able to define "global usings" in a file which will be used for the entire project.

By convention the name of this file is "GlobalUsings.cs", but you can give it any name you like.

For your specific example, if you want MyUser to be an alias for Dictionary<string,string> throughout the project, create a "GlobalUsings.cs" file that contains the following:

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

As per various comments, this might not be a good idea:

  1. Type aliases are not visible outside the current project; anything that uses a type alias will be seen as the original unaliased type outside the assembly.
  2. Just declaring an alias rather than a proper class for anything other than a type that is for generic use will make proper encapsulation of the type's logic impossible.
  3. In your specific example, MyUser seems a bad name for Dictionary<string, string>. Without further information we can't really say much more about this.
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
  • 2
    thats a good answer, but i think you should add that the original problem is solved by that (so is technically possible to do) but could be considered as bad practice (in that situation) – Michael Schönbauer Aug 18 '23 at 08:47
  • 1
    I think this may be related: [Why not inherit from List?](https://stackoverflow.com/q/21692193/982149) and aliasing in this case is kind of the same thing as inheriting. – Fildor Aug 18 '23 at 08:54
  • @Fildor exactly!! that was the link i was searching for for 10 minutes to post it here :D – Michael Schönbauer Aug 18 '23 at 08:55
  • :D That's one of those in my bookmarks. Like a boomerang it keeps coming back. – Fildor Aug 18 '23 at 08:57
  • Yes in this case `MyUser` is a very strange name for a dictionary; I'd call it `StringDictionary` or somesuch, which would be a perfectly valid typedef name. But inheritance is nothing like a typedef IMO. – Matthew Watson Aug 18 '23 at 09:06
  • @MatthewWatson Technically not, of course. That's not what I meant. The _apparent_ (I _could_ be wrong on that) usage (Inherit for the sake of Alias vs typedef) to make an abstraction would have effectively the same arguments against it. Does that make sense? – Fildor Aug 18 '23 at 09:10
  • 2
    Difficult to say here without more details from the OP about how they intend to use this type. I only use global usings as aliases for two reasons: as a shorthand for various often-used types (e.g. `StringDictionary`) and for documentary purposes (e.g. `global using Millimeters = System.Double;` which means that a method such as `double MeasureItem(Item item)` can be `Millimeters MeasureItem(Item item)` which is, of course, more self-documenting. But generally only for `internal` items, because the global usings are per-project. – Matthew Watson Aug 18 '23 at 09:13
  • Yes I am aware I am making some assumptions, there. Just wanted to raise awareness that it _might_ be the case that this isn't _actually_ what OP _should be doing_. Which may or may not apply depending on info I do not have. – Fildor Aug 18 '23 at 09:21
  • Kudos for the edit. I would +1 but I already have :) – Fildor Aug 18 '23 at 09:45
  • but after the edit, it gets my upvote :) – Michael Schönbauer Aug 18 '23 at 09:49
  • @MatthewWatson Thank you . I used the alias MyUser because the data come from Microsoft Active Directory and depend on the request I send. Example: `using (var srch = new DirectorySearcher(dirEnt, filter, proprietesAD)) ` Sometimes I just need ["samaccountname", "sn", "mail"] (=proprietesAD), other times I need more information like ["samaccountname", "sn", "mail", "givenname", "l", "Department", "msExchExtensionAttribute19"] So I decided to store these data in a "flexible" structure I called MyUser ..the result of my query is a List of User ` List ` – Jean-Pierre R Aug 18 '23 at 10:03
0

What about something like this? It also works fine without global using (if you have an older version of C# for example)

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

MyType dictionary = new MyType();
T. Dominik
  • 406
  • 3
  • 13
0

I doubt that this would be good practice in a project involving more people but ignoring this fact, a solution would be to use a using directive like so:

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

namespace ClassLibrary1
{
    public class Class1
    {
        public MyType MyProperty { get; } = new MyType();

        public Class1()
        {
            MyProperty.Add("key", "value");
        }
    }
}

Regarding your snippet:

Type MyUser =typeof(Dictionnary<string,string>);

this will create an object of type Typethat describes the Dictionnary<string,string> type. You cannot then use this instance of Type to initialize a variable.

typeof is just syntactic sugar for Type.GetType(assemblyName).

Basically, your snippet would be analogous to doing this:

namespace ClassLibrary1
{
    public class Class1
    {
    }

    public class Class2
    {
        public Class2()
        {
            var class1 = new Class1();

            // this is not compilable
            class1 class1Instance;
        }
    }
}
AsPas
  • 359
  • 5
  • 22