Reputation: 1402
Consider the following code, the first call to AcceptType1
compiles fine, however the second call of AcceptType1(XYZ);
fails. The specific error is:
Error CS0119 'XYZ' is a type, which is not valid in the given context
I'm not understanding the the specifics behind the error message, and from that I'm failing to understand why the second call fails if XYZ
is a type which is exactly what AcceptType1
accepts. If XYZ
is a type, then why the need to then call typeof
?
public class XYZ
{
}
public class Tester
{
public void RunTest()
{
AcceptType1(typeof(XYZ));
AcceptType1(XYZ);
}
private void AcceptType1(Type t)
{
Console.WriteLine(t.ToString());
}
}
Upvotes: 3
Views: 9322
Reputation: 2713
XYZ
may be a type, but it's not a Type
, which is what your method expects as a parameter. typeof(XYZ)
gives you the Type
for the class XYZ
.
Upvotes: 1
Reputation: 190943
XYZ
is a symbol or name to the class XYZ
. typeof
will get the runtime information about the type, which is System.Type
. You can also pass type symbols with generics, which doesn't work with typeof
:
AcceptType1<T>()
where T
can be filled in with a type symbol or name.
Upvotes: 8