Why "typeof(C)" and "C.class" are needed?

Some languages like C# and Java use a special notation for getting a type object from a type identifier, like “typeof©”. But why is is not the identifier directly? Does someone know?

For generic functions you also just need the identifier. I have some ideas why, but I am not sure.

1 Like

I could imagine it’s a parsing issue. E.g. in Java annotation parameters, you don’t want to allow arbitary expressions, but only literals and class references.

I reflected a bit. And I think you are right… if everything would be an expression, it would be hard to determine all necessary type information.

Another thing is to talk about metamodeling. Instead of properties A, B, C you get an array of PropertyInfo.

It’s just for added clarity for humans.
class C {}

C C = new C();
print( C ); // <- is this the class or the variable?

Of course you can avoid this problem using coding conventions, and some languages (e.g., Groovy) do use the established convention to avoid the .class syntax.

This is just the old Lisp-1 vs Lisp-2 debate in disguise (see e.g. https://groups.google.com/u/1/g/elixir-lang-core/c/HzUEAVmbD00?pli=1 for a modern explanation). There’s no “right” way – some people will prefer one, some the other.

Next to parsing issues; A type literal like JavaClass.class also has a special static type property, namely that it returns an instance of Class<JavaClass> and not Class<?> as it would do if it were comparable to a runtime dereference. So the .class literal is for literal types only, And it returns a representation of the type with a most concrete static type parameter of the Class Type kind.

This then has its uses in java, to be able to statically bind type parameters by passing type literals as parameters to methods. Like <T> T cast(Class<T> type, Object o) { return (T) o; }