0

C# I am using a dictionary like:

var dict = new Dictionary<byte, Tuple<string, string>>();           
Tuple<string, string> t = new Tuple<string, string>(label, unit);

I want to declare it as a data member of the class. but it says

The contextual keyword 'var' may only appear within a local variable declaration or in script code

How do I solve this?

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
Sayan Sen
  • 1,654
  • 3
  • 16
  • 26
  • 4
    Try `Dictionary> dict = new Dictionary>();`. In class field declaration you cannot use `var`. – Alessandro D'Andria Jul 16 '18 at 09:43
  • 1
    Just as it says use var only as a local variable declaration or in script code. Other than that, use the type itself. – Cetin Basoz Jul 16 '18 at 09:44
  • You declare it in class or inside a function as local variable? If in class, the variable should be not using var, you should Dictionary> dict = new Dictionary>(); – Ong Ming Soon Jul 16 '18 at 09:45

2 Answers2

3

The error message is pretty clear. You cannot use var to declare class members, only for local variables.

For class members you need to use the explicit type:

public class MyClass
{
    Dictionary<byte, Tuple<string, string>> dict = new Dictionary<byte, Tuple<string, string>>();

    // ...
}
René Vogt
  • 43,056
  • 14
  • 77
  • 99
3

in C# you cannot use var to declare class members:

here are technical issues with implementing this feature. The common cases seem simple but the tougher cases (e.g., fields referencing other fields in chains or cycles, expressions which contain anonymous types) are not.

taken from the blog post Why no var on fields? and from this post.

In such case, you need to declare explicit types:

Dictionary<byte, Tuple<string, string>> dict = new Dictionary<byte, Tuple<string, string>>();
Barr J
  • 10,636
  • 1
  • 28
  • 46