-1

I have met a issues that I couldn't declare var into Dictionary in c#. Is there any way to declare a implicity datatype in Dictionary in c#?

The current declaration of my codes

IDictionary<string, var> serializeMetadata = new Dictionary<string, var>();

With the shown code, my Visual Studio IDE returns an error of

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

Wayne Lee
  • 1
  • 4
  • you'd better provide more context, i.e. why you want such dict. – Lei Yang Mar 17 '22 at 04:54
  • The error message suggests this is a field and not a local variable? You can't use type inference when defining class members and, otherwise, you can't use `var` for a type parameter. Are you immediately populating `serializeMetadata` with entries of the desired type? If so, you could potentially define the variable as `var serializeMetadata = ...` and then use, say, `.ToDictionary()` to build a dictionary out of some input without specifying the type. At some point that input type would need to either be known or a type parameter itself, though. You'll need to show more code in that case – Lance U. Matthews Mar 17 '22 at 04:57
  • @LeiYang the purpose of using such dict is to cope with my ever changing Json file. I would like to read and copy out certain objects that are matched for my requirement and then paste to a new json file that i created for another purposes. – Wayne Lee Mar 17 '22 at 04:59
  • can you put those context in the question, instead of comment. also [ExpandoObject](https://stackoverflow.com/a/10253036/1518100) may be help. – Lei Yang Mar 17 '22 at 05:03
  • If it's only json-processing without using the objects in your C#, try simply deserialize it, put whatever you want into `List` or `Dictionary`, then serialize it again. I use `Newtonsoft.Json` and it can serialize `List` with `object`s read as each one's derived class. However I deserialize my json into a defined type though... You might have to test around. Reference: https://stackoverflow.com/a/44411008/16606026 – Xiang Wei Huang Mar 17 '22 at 05:25

2 Answers2

1

You can use object:

var serializeMetadata = new Dictionary<string, object>();
Patrick
  • 5,526
  • 14
  • 64
  • 101
  • but what if one of the key value pair is containing an array? Can you please elaborate? – Wayne Lee Mar 17 '22 at 04:48
  • That's not the same, though. Among other reasons, what if `var` would be a value type? Or if the `var` type always is and must be guaranteed (by the compiler) to be the same type? – Lance U. Matthews Mar 17 '22 at 04:49
1

You can use object. Below is the basic example:-

Dictionary<string, object> storage = new Dictionary<string,object>();

storage.Add("age", 12);
storage.Add("name", "test");
storage.Add("bmi", 24.1);

int a = (int)storage["age"];
string b = (string)storage["name"];
double c = (double)storage["bmi"];
Aditya Jain
  • 105
  • 9