IamIC
IamIC

Reputation: 18269

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.

Upvotes: 3

Views: 187

Answers (2)

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174477

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.

Upvotes: 4

TGH
TGH

Reputation: 39278

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>

Upvotes: 4

Related Questions