Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a namespace-wide C# alias?

Tags:

c#

.net

alias

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.

like image 538
sgtz Avatar asked Jun 24 '12 11:06

sgtz


2 Answers

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(...).

like image 162
Tim S. Avatar answered Oct 01 '22 23:10

Tim S.


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.

like image 26
usr Avatar answered Oct 02 '22 00:10

usr