this post was submitted on 16 Jun 2023
6 points (100.0% liked)

C Sharp

1512 readers
17 users here now

A community about the C# programming language

Getting started

Useful resources

IDEs and code editors

Tools

Rules

Related communities

founded 1 year ago
MODERATORS
 

Another one of my C# articles, this time about Nullable.

top 4 comments
sorted by: hot top controversial new old
[โ€“] porgamrer 2 points 1 year ago (1 children)

I've found C# nullable types quite frustrating, because nullable generics don't work properly when they can be instantiated with both value types and reference types.

It feels like a very hacky approximation of an option type, which we are now probably stuck with. Compared to all the other amazing features they've added, that one felt a bit half baked.

[โ€“] [email protected] 2 points 1 year ago

To be honest I feel the same way about it now.

[โ€“] CatPoop 2 points 1 year ago* (last edited 1 year ago) (1 children)

I really like nullable types, they can be very effective for writing safer code.

Sometimes there are good reasons to separate object construction and initialization (e.g. composite / loosely coupled objects, or encapsulation of 3rd party libraries) so there can be properties/fields that do not yet have valid values, and using separate queries for this is error prone.

I write a lot of communication interfaces for sensors/actuators and if the communication drops, nullables are a good way to represent invalid readings.

Being able to convey the value and validity in one variable can be more thread-safe and easier to write pure-functions, and show intent.

I occasionally use a nullable for singleton patterns if Iโ€™m not 100% convinced there can never be multiple instances, rather than painting myself into a corner with a static class. e.g.

public static MyClass Instance => _instance ??= new();
private static MyClass? _instance; 
[โ€“] [email protected] 1 points 1 year ago* (last edited 1 year ago)

Those who are trying to avoid milk should consider using Lazy<MyClass> _instance;

load more comments
view more: next โ€บ