Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to alias array type in c#?

I'm trying to do some serialization / deserialization stuff with a custom exception type. This type has a field defined as:

private object[] resourceMessageParams;

I've got all nice and strongly typed code with some Linq expression magic, but I want to go even further than that and do something like this:

using ResourceMessageParamsType = object[];//<-- "Identifier expected" error here
/*...*/
private ResourceMessageParamsType resourceMessageParams;
/*...*/
this.resourceMessageParams = 
    (ResourceMessageParamsType)serializationInfo.GetValue(
        ReflectionHelper.GetPropertyNameFromExpression(() => 
            resourceMessageParams), typeof(ResourceMessageParamsType));

Instead of this:

(object[])serializationInfo.GetValue(
    ReflectionHelper.GetPropertyNameFromExpression(() => 
        resourceMessageParams), typeof(object[]));

To accomodate for possible change of type of this field in the future, so one will have to change the type only once in alias definition. However, the compiler stops at object in using ResourceMessageType = object[]; complaining that an identifier is expected. Changing to Object[] helps somewhat, but this time the bracket is highlighted with the same error message.

Is there a way to define an alias for array type in c#?

like image 428
Stanislav Kniazev Avatar asked Apr 13 '11 21:04

Stanislav Kniazev


2 Answers

You could define a class (or struct) called ResourceMessageParamsType and define implicit operators for casting to and from object[].

struct ResourceMessageParamsType
{
    private object[] value;

    private ResourceMessageParamsType(object[] value)
    {
        this.value = value;
    }

    public static implicit operator object[](ResourceMessageParamsType t)
    {
        return t.value;
    }

    public static implicit operator ResourceMessageParamsType(object[] value)
    {
        return new ResourceMessageParamsType(value);
    }
}
like image 199
tuxedo25 Avatar answered Nov 06 '22 01:11

tuxedo25


Simply put, you can't "alias" array types.

You can work around it by encapsulating things in a struct, but that doesn't answer your question.


Update:

From the ECMA standard,

using-alias-directive:

using identifier = namespace-or-type-name ;

which clearly doesn't say anything about arrays being permitted.

(See page 100 for how namespace-or-type-name is defined.)

like image 21
user541686 Avatar answered Nov 06 '22 01:11

user541686