Chawin
Chawin

Reputation: 1466

Compiler error when inheriting from ConcurrentDictionary

class Test<string, T> : System.Collections.Concurrent.ConcurrentDictionary<string, T>

The above code returns the two errors:

However, capitalising the string within Test produces no errors.

class Test<String, T> : System.Collections.Concurrent.ConcurrentDictionary<string, T>

Can anybody explain as to why the compiler would be producing these errors when string is lowercase, but not when uppercase?

Upvotes: 1

Views: 266

Answers (1)

Servy
Servy

Reputation: 203802

When you write class Test<string, T> you're attempting to define a new type argument and name that type argument string. string isn't a valid identifier for a type, because it's a reserved word in the language. String isn't a reserved word in the language; it's a valid name for you to give your new type argument, so the code works.

Or at least, "works" in the sense that you've now named your new type alias String. But you don't actually want to do that; you don't want to have a new type argument named String, you just want to have the key of your dictionary be a String, so simply don't define a new type argument at all:

class Test<T> : System.Collections.Concurrent.ConcurrentDictionary<string, T>

On a related note, you probably shouldn't be inheriting from ConcurrentDictionary at all. It's not a type that was designed to be inherited from. You probably just want to compose one, and have your own type that simply has a ConcurrentDictionary as a field.

Upvotes: 7

Related Questions