Question

How might one go about aliasing a type in VB.NET or C# such that when the alias is used as an argument type in a function, accidentally using the not aliased type is an error?

i.e.

Imports AccessSpecifier = System.String

Module Accessors
    Delegate Function IoOper(ByRef strm As System.IO.Stream) As Action
    Public Function accessMethod(ByRef spec As AccessSpecifier) As IoOper
        ' implementation
        ' ...
    End Function
End Module

Module Main
    Public Sub Main()
        Dim spec As AccessSpecifier = New AccessSpecifier(CType("READ_WRITE", Char()))
        Dim val = Accessors.accessMethod(spec)
        System.Console.WriteLine(val.GetType())
        Dim shouldFail = Accessors.accessMethod("FAIL_ME")
        System.Console.WriteLine(shouldFail.GetType())
    End Sub
End Module

Or perhaps is there a better way to go about this?

Overall, I'm wanting the IDE to force me to know what I'm doing if I'm throwing Ints around to mean Flags, or States and Strings around to mean Names, Propertys and Records.

Help?

Was it helpful?

Solution

I've never liked Type aliasing in .NET. It makes for imprecise code and it is not immediately clear what is happening. As in your example, when an individual went looking for the AccessSpecifier.vb file (or class) they would not find it.

Also, Aliasing only works within YOUR project and only within a single code file. So you would have to define that alias in all the various code files where it was to be used.

A better (as in easier to read, easier to maintain, and more clear of intent) option is to create a class and overload the type conversion operators for automatic conversion to/from String. In this manner you retain your ability to use your new class as if it were a String, but you gain your strict type checking.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top