Given a generic type, including
List<string>
Nullable<Int32>
how do i get a generic name for C#?
var t = typeof(Nullable<DateTime>);
var s = t.GetGenericTypeDefinition().Name + "<" + t.GetGenericArguments()[0].Name + ">";
This yields
"Nullable`1<DateTime>"
, but i need
"Nullable<DateTime>"
.
While the accepted solution is good for just the name or for a non nested full name (by replacing name to full name as in @Ose E's answer), however for nested types it will still not work, and also not for arrays of generic types.
So here is a solution that will work, (but note that this solution will only set the actual arguments, only if all arguments are set, and in other words even if the declaring type has supplied type arguemts, as long as the innermost generic type has not, it will still not show up even for the base).
Minor addition to @Aaronaught
This is my solution, it's also working for nested classes and generics:
This will result in exactly the same code result like the cs code generator. I've improved the code of yoel halb.
this will pass the following unit test as expected.
Result will be:
I see you already accepted an answer, but honestly, that answer isn't going to be enough to do this reliably if you just combine what's in there with what you already wrote. It's on the right track, but your code will only work for generic types with exactly one generic parameter, and it will only work when the generic type parameter itself is not generic!
This is a function (written as an extension method) that should actually work in all cases:
This function is recursive and safe. If you run it on this input:
You get this (correct) output: