It's possible to define an alias in C# like this
using kvp = System.Collections.Generic.KeyValuePair<string, string>;
var pair = new kvp("key", "value");
Microsoft define aliases too:
int i;
Int32 i2;
How can we define aliases that are available within a namespace? Is this configurable?
This question is specifically about an alias... so... using inheritance as a proxy isn't desired. I'm happy with that in many situations... but not when you want the best of both descriptive names and a shorthand version.
I don't think that what you're asking for is really possible. Here's a workaround: include a type called kvp that is a copy of KeyValuePair<string, string>
and implicitly converts to and from your type.
public struct kvp
{
public string Key { get; private set; }
public string Value { get; private set; }
public kvp(string key, string value)
: this()
{
Key = key;
Value = value;
}
public override string ToString()
{
return ((KeyValuePair<string, string>)this).ToString();
}
public static implicit operator KeyValuePair<string, string>(kvp k)
{
return new KeyValuePair<string, string>(k.Key, k.Value);
}
public static implicit operator kvp(KeyValuePair<string, string> k)
{
return new kvp(k.Key, k.Value);
}
}
This has the effect of you being able to use kvp
instead of KeyValuePair<string, string>
, with no unintended effects in most cases.
If the type you wished to typedef were an unsealed class, you could do (something very close to) what you want by making a class that extends it, with all of the base class's constructors mirrored and extending base(...)
.
You are explicitly asking for an alias and not for a workaround. Therefore, the only answer I have is: There is no way to do this.
The using
alias that you gave as an example is per file. C# does not have a construct that allows cross-file aliases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With