samwyse
samwyse

Reputation: 2996

Using type aliases to define type aliases

As a fanatical believer in DRY (Don't Repeat Yourself), I just wrote this code:

Imports SimpleDict = System.Collections.Generic.Dictionary(Of String, String)
Imports ListOfSimpleDicts = System.Collections.Generic.List(Of SimpleDict)
Imports DictOfSimpleDicts = System.Collections.Generic.Dictionary(Of String, SimpleDict)

I immediately get errors, "Type 'SimpleDict' is not defined." on the last two lines. Is there no way to avoid having to repeat myself in my type aliases?

[Addendum] 24 hours later, I had to change SimpleDict to alias Dictionary(Of String, HashSet). The good news is, since I'm using an alias, my change propagates to everywhere I've used it, but unfortunately I still need to change the other two lines myself.

Upvotes: 3

Views: 1882

Answers (1)

singularhum
singularhum

Reputation: 5122

From the VB specification

Imports statements make names available in a source file, but do not declare anything in the global namespace's declaration space. The scope of the names imported by an Imports statement extends over the namespace member declarations contained in the source file. The scope of an Imports statement specifically does not include other Imports statements, nor does it include other source files. Imports statements may not refer to one another.

In this example, the last Imports statement is in error because it is not affected by the first import alias.

Imports R1 = N1 ' OK.
Imports R2 = N1.N2 ' OK.
Imports R3 = R1.N2 ' Error: Can't refer to R1.

I'm not sure what you could do instead. The only thing I could think of is defining SimpleDict as a class of System.Collections.Generic.Dictionary(Of String, String), not sure if this is ideal for you since you have to create a class.

Imports ListOfSimpleDicts = System.Collections.Generic.List(Of RootNamespace.SimpleDict)
Imports DictOfSimpleDicts = System.Collections.Generic.Dictionary(Of String, RootNamespace.SimpleDict)

Public Class SimpleDict
    Inherits System.Collections.Generic.Dictionary(Of String, String)
End Class

Upvotes: 3

Related Questions