Jonathan Tuzman
Jonathan Tuzman

Reputation: 13287

Share Type Alias among different files in one namespace

I have defined a type alias, and I can use it in my class that I've declared in this file.

using TemplateStructure = System.Collections.Generic.List<System.Collections.Generic.List<DataManagement.TemplateImageLocation>>;

namespace Gui.ViewModels
{
    public class AddRemoveCellsViewModel : TemplateWorkflowStepViewModel
    {
        public TemplateViewModel TemplateVM
        {
            get;
        }

        public AddRemoveCellsViewModel(TemplateStructure locations) : base(locations)
        {
            base.DisplayName = "Add and Remove Rows/Columns";
            TemplateVM = new TemplateViewModel();
        }
    }
}

But another class in another file, in the same namespace, it doesn't work.

namespace Gui.ViewModels
{
    public class ActivateDeactivateCellsViewModel : TemplateWorkflowStepViewModel
    {
        // FAILS
        public ActivateDeactivateCellsViewModel(TemplateStructure locations) : base(locations)
        {
            base.DisplayName = "Click to deactivate image locations";
        }
    }
}

And, of course, usings must be placed outside of a namespace declaration.

Is it possible to use this Type Alias in multiple files?

Upvotes: 1

Views: 490

Answers (1)

Sweeper
Sweeper

Reputation: 273380

You have to write

using TemplateStructure = System.Collections.Generic.List<System.Collections.Generic.List<DataManagement.TemplateImageLocation>>;

In every file where you want to use this alias, because

A using_alias_directive introduces an identifier that serves as an alias for a namespace or type within the immediately enclosing compilation unit or namespace body.

(from C# Language Specification - Using alias directives)

Using-aliases do not work across compilation-units, which are:

A C# program consists of one or more compilation units, each contained in a separate source file.

(from C# Language Specification - Compilation units)

Upvotes: 3

Related Questions