Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an alias for a complex type without subclassing?

Tags:

c#

alias

I have a complex type in my program that results in very long line lengths. Here it is:

List<FruitCallback<Fruit>>

Here's an example of where the line of code is simply too long and confusing:

private static Dictionary<Type, List<FruitCallback<Fruit>>> callbacks = new Dictionary<Type, List<FruitCallback<Fruit>>>();

I can create an alias for it by subclassing it like so:

class FruitCallbacks : List<SomeClass.FruitCallback<Fruit>> { }

But I could of sworn I remember reading somewhere about a way to alias something like this such that an empty class would not be necessary.

like image 421
Ryan Peschel Avatar asked Oct 19 '11 23:10

Ryan Peschel


2 Answers

You can add a fully qualified using statement to your class file (in the using directives section) to alias the class. It's a bit verbose.

using MyType = System.Collections.Generic.List<YourNamespace.FruitCallback<YourNamespace.Fruit>>;

And then you can MyType in place of List<FruitCallback<Fruit>> in your code.

Full working example.

// aliased outside the namespace
using MyList = System.Collections.Generic.List<Bar.FruitCallBack<Bar.Fruit>>;

namespace Bar
{
    // alternately, can be aliased inside the namespace 
    // using MyList = System.Collections.Generic.List<FruitCallBack<Fruit>>;        

    class Program
    {
        static void Main()
        {
            var myList = new MyList();
        }
    }

    public class FruitCallBack<T> { }
    public class Fruit { }
}
like image 117
Anthony Pegram Avatar answered Oct 13 '22 03:10

Anthony Pegram


you can do this:

using Foo =  List<FruitCallback<Fruit>>;

Then you can use Foo everywhere you need to use List<FruitCallback<Fruit>> Example:

using System;
using System.Collections.Generic;
using Foo =  List<FruitCallback<Fruit>>;

class Program
{
    static void Main()
    {
      Foo f = new Foo();
    }
}
like image 32
DarthVader Avatar answered Oct 13 '22 03:10

DarthVader