1

The syntax T? is shorthand for Nullable<T>. Is there a way I can do something similar to this, but with my own custom characters/etc.?

Like making T! shorthand for MyGeneric<T>.

ATD
  • 824
  • 1
  • 9
  • 14
  • 2
    Nope. You can use Roslyn to do pre-processing, but that's about it. http://stackoverflow.com/questions/11749222/is-there-a-way-to-implement-custom-language-features-in-c – vcsjones Nov 17 '15 at 22:02
  • No. There is feature request to allow "using" [aliases for unbounded generics](https://github.com/dotnet/roslyn/issues/3993). – Mike Zboray Nov 17 '15 at 22:09

2 Answers2

0

You can, in a sense. You are not able to use ! because it is not a valid character for identifiers but you could use any other valid characters. That being said, this is very limited. If you know a base type that you are going to use, you can do:

using @c = System.Collections.Generic.List<B>;

Where B is the base class. If you want a more generic version you could do:

using @c = System.Collections.Generic.List<object>;

You could now use @c as if it is a List<B> or `List'. Such as:

@c a = new @c;
a.Add(new B());

Like I said, it is limited and not practical but it is semi-possible.

Jetti
  • 2,418
  • 1
  • 17
  • 25
  • 1
    Why are you using the `@` operator for the identifier `c`? – Servy Nov 17 '15 at 22:06
  • 2
    while this is possible... I'm pretty sure if I ever came across this in code I would hunt down the dev and smack the crap out of them. – Matthew Whited Nov 17 '15 at 22:07
  • The `@` is not actually part of the identifier. You could write `c a = new c()` and have it work just as well. The `@` is simply indicates to the compiler that the token is an identifier and not to be treated as a keyword. – Mike Zboray Nov 17 '15 at 22:21
  • @Servy because the original post had unique characters in it so I figured I would show what is possible. – Jetti Nov 18 '15 at 00:29
  • 1
    @MatthewWhited The premise of the question would make me do the same! – Jetti Nov 18 '15 at 00:29
  • @mikez good to know. I just chose the `@` because it was something that stuck out, similar to the `!` that was used in the original post – Jetti Nov 18 '15 at 00:30
  • @Jetti The use of `@` in no way allows `!` to be used in an identifier, or any other characters that wouldn't otherwise be valid in an identifier. – Servy Nov 18 '15 at 00:55
  • @Servy I understand that. I had no intention to use an invalid identifier character but was using a valid identifier character to differentiate from other identifiers. – Jetti Nov 18 '15 at 14:42
0

This can't be done unless you use Roslyn. I believe the closest thing (correct me if I'm wrong) to what you want is something like this:

using YourAlias = System.Collections.Generic.Dictionary<string, string>; // or whatever type you want

and to use it:

var dict = new YourAlias();
Servy
  • 202,030
  • 26
  • 332
  • 449
Jonathan Carroll
  • 880
  • 1
  • 5
  • 20