C# Refreshers12 Oct 2023
I had an interview recently that really challenged me. The interview was a collaborative coding challenge using C#. I was reminded of many C# features (datatypes, operators, etc), and I was taught about principles & performance characteristics. I outline these below because they inspired me!
Some reserved keywords:
eventis a reserved keyword
Null Coalescing Operator
More here Some examples:
A variation on the
. member access operator
It can also be used for index access operator
Error with Chaining Null-Conditional
I thought this operator couldn’t be used on every type. I got an error on this line:
SortedEventsByTicker // a SortedList<TKey,TValue> .GetValueOrDefault(EventTicker) ?.LastOrDefault() ?.Value // <--------- error
The error was:
Operator ‘?’ cannot be applied to operand of type ‘KeyValuePair<long, Solution.TradingEvent>’
- Maybe the error is because
?.is executed right-to-left (does that mean it’s right-associative?)
- Is this error specific to replit; maybe the C# interpreter it is using??
- TODO: Check a simpler case on replit; check the same case with different C# interpreter
I fixed the error by adding parentheses, which is why I thought associativity was part of the problem…
(SortedEventsByTicker // a SortedList<TKey,TValue> .GetValueOrDefault(EventTicker) ?.LastOrDefault()) // <------- parentheses ?.Value
It’s also interesting to learn that
?. is “short-circuiting”.
- Does short-circuiting mean I can avoid “chaining” the operator like
A?.B?.DoSomething(C), can I just do
- No, I don’t think so.
- Note short-circuiting is explicitly broken using the parentheses as I did above
if the chained member access is interrupted, for example by parentheses as in (A?.B).C(), short-circuiting doesn’t happen.
More on the
LastOrDefault method here
The default value for reference and nullable types is null. The LastOrDefault method does not provide a way to specify a default value. If you want to specify a default value other than default(TSource), use the
DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource)method as described in the Example section.
Classes (Reference Types) are Nullable
More here. Just a quick reminder. Other “primitive” types must be made nullable using the
? operator like
System.Collections.Generic Datatypes & Performance Characteristics
Inserting into a List is:
- TODO Confirm
- TODO Link the Python algorithms book
- TODO describe “amortized”
- O(1) if list need not be reallocated
- O(n) if list needs to be reallocated
I hadn’t used