Follow

Java:

HashMap<Integer, String> m = new HashMap<>();
m.put(1, "one");

C#:

Dictionary<int, string> d = new Dictionary<int, string>();
d.Add(1, "one");

Okay, fine so far...

Java:

String s = m.get(1);

C#:

String s;
m.TryGetValue(1, out s);

@peterdrake I mean, you could just access it by key like Java as well, but the csharp line is wrapping up a key check and get in one there, so the Java line would need a containsKey around it. Scala would use a getOrElse etc…

@peterdrake you could also use “out var s” as well so you don’t have to declare the string variable above

@dazfuller That's the thing -- C#'s Dictionary class doesn't seem to have a Get method, so you have to do this out business.

@peterdrake it’s just square brackets, so myDict[1] and you’re done

@dazfuller @peterdrake Hahaha... I've never seen the "OrElse" name and I just love that it sounds like a threat! 😂

I usually have an Extension Method in C# for GetOrDefault().

@wkfry @peterdrake I always imagine grandpa Simpson waving a fist at the sky when I write it

@peterdrake c#

String s = m[1]

Although tryGetValue is preferable unless you know that the key is in the dictionary

@peterdrake Also with c#
var d = new Dictionary<int, string>();
or
Dictionary<int, string> d = new();

@peterdrake With TryGetValue you should really check the function result to see whether the key is actually present in the dictionary. Otherwise you'll just get default values which might not be something you want.

@peterdrake tbh the equivalent of that Java code in C# is the following:

var d = new Dictionary<int, string>();

d[1] = "one";

var s = d[1];

Sign in to participate in the conversation
Qoto Mastodon

QOTO: Question Others to Teach Ourselves
An inclusive, Academic Freedom, instance
All cultures welcome.
Hate speech and harassment strictly forbidden.