Equivalent of typedef in C#
No, there's no true equivalent of typedef. You can use 'using' directives within one file, e.g.
using CustomerList = System.Collections.Generic.List<Customer>;
but that will only impact that source file. In C and C++, my experience is that typedef
is usually used within .h files which are included widely - so a single typedef
can be used over a whole project. That ability does not exist in C#, because there's no #include
functionality in C# that would allow you to include the using
directives from one file in another.
Fortunately, the example you give does have a fix - implicit method group conversion. You can change your event subscription line to just:
gcInt.MyEvent += gcInt_MyEvent;
:)
Jon really gave a nice solution, I didn't know you could do that!
At times what I resorted to was inheriting from the class and creating its constructors. E.g.
public class FooList : List<Foo> { ... }
Not the best solution (unless your assembly gets used by other people), but it works.
If you know what you're doing, you can define a class with implicit operators to convert between the alias class and the actual class.
class TypedefString // Example with a string "typedef"
{
private string Value = "";
public static implicit operator string(TypedefString ts)
{
return ((ts == null) ? null : ts.Value);
}
public static implicit operator TypedefString(string val)
{
return new TypedefString { Value = val };
}
}
I don't actually endorse this and haven't ever used something like this, but this could probably work for some specific circumstances.