@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 comparing apples and oranges here… the analog to the java one would be
m[1]
What you picked is the try..get pattern used e.g. like this:
if (m.TryGetValue(1, out var val)) return val;
else return „fallback“, or, shorter
return m.TryGetValue(1, out var val) ? val : „fallback“;
@flq Yeah, I was just looking in the API for Dictionary and wondering why, if there was an Add method, there was no Get method. I had forgotten about square bracket access.
@peterdrake @flq why not edit your original post then? Or delete it, since it's now rendered pointless?
@damselfly @flq My server is running variant software that doesn't allow editing posts. I might delete it, but could someone else who overlooked the same thing benefit from the replies?
@peterdrake @flq Nobody reads the replies. 😉
Maybe get a better server?
@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];
@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…