Assume I have the type
public class A<T> { }
and somewhere in the code I want to throw an exception related to incorrect usage of that type:
throw new InvalidOperationException("Cannot use A<T> like that.");
So far, so good, but I don't want to hardcode the classes name, so I thought I could maybe use
throw new InvalidOperationException($"Cannot use {nameof(A<T>)} like that.");
instead, but in this context I don't know the exact type T
.
So I thought maybe I could do it with template specialization like in C++:
throw new InvalidOperationException($"Cannot use {nameof(A)} like that.");
or
throw new InvalidOperationException($"Cannot use {nameof(A<>)} like that.");
but those yield
Incorrect number of type parameters.
and
Type argument is missing.
I absolutely don't want to hardcode the classes name for it might change later. How can I get the name of the class, preferably via nameof
?
Optimally, what I want to achieve is "Cannot use A<T> like that."
or "Cannot use A like that."
.
A
in that particular case at all. – Delwinnameof(type)
is compiled into the assembly, so it is hardcoded, but in the assembly. Runtime it can be considered a constant. – CitizenA
's name in the IDE, it will change all the ``nameof(type)` with it, which would not be a case for a "develop-time" constant. – DelwinA<T>
objects? Just asking since if you want this as a warning to developers, throwing an exception only warns them when they try to run it. It seems like you could resolve this be restricting the Type of T or the types of the parameters used by methods whereA<T>
is being erroneously passed. Anyway design questions probably off topic to the question. – Punchball