Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Just re-read C# documentation and remembered the situation more clearly.

Basically, I consciously researched the differences between class and struct in C# beforehand. And decided to use struct as the 'thing' was a kind of a coordinate that would be instantiated a lot for simple coordinate-space transformations, so it made sense for it to actually be a value type.

I should've been more assertive about it. Well, worst case some periodic imports are taking somewhat longer than they should.



Just to add some context. Another commenter mentioned gotchas that would make C# developers weary.

The fist that comes to mind is that with a class invariants of the type can be ensured in the constructor or by making the constructor private and exposing static factory methods. A struct, on the other hand, is always simply declared, so don't afford these protection measures. For some reason C# still supports constructors in structs though, and even uses the `new` keyword to invoke them. This creates a kind of trap where structs almost, but not quite, behaves like classes.

Another gotcha is the defensive copy semantics. When a method is invoked on a struct, and that struct is a readonly field, a copy of the struct is created for the method to avoid mutating the field. This is not at all how classes referenced by a readonly field behaves.

I guess the same can be said for the simpler case of just passing a struct as parameter to a method mutating its now local copy. Again different outcome for structs and classes.

Since the code look so similar (its just a different keyword at declaration site) it creates an uncanny valley tripping people up. Not least when refactoring between the two. After all, being a language with a GC means memory layout is seldom a primary concern for people.

However you can now declare structs readonly to avoid the defensive copy thing, or as a ref-struct to retain mutability, almost like a class. And as long as the default value is perfectly valid, like say (0,0) there shouldn't be much surprises anymore.


That's different, and in that case a struct is preferred.

Don't confuse inexperience with culture.

I'm from a mostly-.NET background I argue with typical .NET developers all the time.

I also argue with Java developers, and C++ developers, and...


C# 9 and 10 added records, which is better for pure data objects.

https://docs.microsoft.com/en-us/dotnet/csharp/language-refe...




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: