Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# can a class be aliased (not with 'using')

In Delphi, the following is possible:

class Alias = Dictionary<long, object>;

Alias is now a dictionary<long, object>.

Is this possible in C#? I've never figured out how without having to wrap the dictionary into a custom class.

The using directive won't work since it's local to the file it appears in.

like image 765
IamIC Avatar asked Dec 01 '25 00:12

IamIC


2 Answers

Not exactly.

But you can do this:

public class Alias : Dictionary<long, object>
{
}

This means you can use Alias everywhere an instance of a Dictionary<long, object> is required. But you can't use a Dictionary<long, object> where an Alias is required.

However, you could create an implicit operator to transparently convert from a Dictionary<long, object> to an Alias instance:

public class Alias : Dictionary<long, object>
{
    public Alias() {}
    public Alias(Dictionary<long, object> dictionary)
    {
        foreach(var kvp in dictionary)
            Add(kvp);
    }

    public static implicit operator Alias (Dictionary<long, object> dictionary)
    {
        return new Alias(dictionary);
    }
}

Please note that this implicit conversion operator will create a copy of the dictionary which might be unexpected or undesired.

like image 84
Daniel Hilgarth Avatar answered Dec 02 '25 13:12

Daniel Hilgarth


No this is not valid in C#.

If you want Alias to be a Dictionary you can inherit the Dictionary class like so.

public class Alias : Dictionary<long, object>
like image 43
TGH Avatar answered Dec 02 '25 15:12

TGH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!