Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the generic type 'System.Collections.Generic.Dictionary< TKey, TValue>' requires 2 type arguments

Tags:

c#

dictionary

I get the error Using the generic type 'System.Collections.Generic.Dictionary< TKey, TValue>' requires 2 type arguments with this line of code:

this._logfileDict = new Dictionary();

I am just trying to have a clear _logfileDict with no entries in it in my code, so that is why I am assigning it a new Dictionary, which will be empty, but if anybody knows some code I could use to just empty _logfileDict otherwise. Its just a dictionary declared as follows:

private Dictionary<string, LogFile> _logfileDict;

Any help is much appreciated!

like image 802
DukeOfMarmalade Avatar asked Nov 16 '11 14:11

DukeOfMarmalade


People also ask

What is TKey and TValue in C#?

The Dictionary<TKey, TValue> Class in C# is a collection of Keys and Values. It is a generic collection class in the System. Collections. Generic namespace. The Dictionary <TKey, TValue> generic class provides a mapping from a set of keys to a set of values.

What is dictionary in C# with example?

In C#, Dictionary is a generic collection which is generally used to store key/value pairs. The working of Dictionary is quite similar to the non-generic hashtable. The advantage of Dictionary is, it is generic type. Dictionary is defined under System. Collection.

What is an IDictionary?

IDictionary Interface is an interface that belongs to the collection module where we can access the elements by keys. Or we can say that the IDictionary interface is a collection of key/value pairs.


2 Answers

The reason you are getting this error is because you are attempting to use the Dictionary<TKey, TValue> class which requires generic type arguments and there is no Dictionary class which does not require generic type arguments.

When using a class which uses generic type arguments you are required to supply the types you want to use whenever you declare or instantiate a variable dealing with the class.

Replace:

this._logfileDict = new Dictionary();

With:

this._logfileDict = new Dictionary<string, LogFile>();
like image 92
Johannes Kommer Avatar answered Oct 26 '22 12:10

Johannes Kommer


There is no type Dictionary without generic parameters in the .NET Framework. You must explicitly state the type parameters when instantiating and instance of Dictionary<TKey, TValue>. In your case, _logfileDict is declared as Dictionary<string, LogFile> and therefore you must explicitly state this when you assign a new instance of it. Therefore, you must assign to _logfileDict a new instance thusly:

this._logfileDict = new Dictionary<string, LogFile>();

(Note, however, there is a System.Collections.Hashtable in the .NET Framework if you don't want to specify the type of the keys and values.)

like image 39
jason Avatar answered Oct 26 '22 13:10

jason