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.
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.
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:
MyUser
seems a bad name for Dictionary<string, string>
. Without further information we can't really say much more about this.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();
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 Type
that 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;
}
}
}