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

This is tangential but one thing that bothers me about C# is that you can declare a `readonly struct` but not a `readonly class`. You can also declare an `in` param to specify a passed-in `struct` can’t be mutated but again there’s nothing for `class`.

It may be beside the point. In my experience, the best developers in corporate environments care about things like this but for the masses it’s mutable code and global state all the way down. Delivering features quickly with poor practices is often easier to reward than late but robust projects.



`readonly class` exists in C# today and is called (just) `record`.

`in` already implies the reference cannot be mutated, which is the bit that actually passes to the function. (Also the only reason you would need `in` and not just a normal function parameter for a class.) If you want to assert the function is given only a `record` there's no type constraint for that today, but you'd mostly only need such a type constraint if you are doing Reflection and Reflection would already tell you there are no public setters on any `record` you pass it.


I'm not sure if it's what you mean, but can't you have all your properties without a setter, and only init them inside the constructor for example ?

Would your 'readonly' annotation dictate that at compile time ?

eg

class Test {

  private readonly string _testString {get;}


  public Test(string tstSrting) 
      => _testString = tstSrting ;
}

We may be going off topic though. As I understand objects in typescript/js are explicitly mutable as expected to be via the interpertor. But will try and play with it.


I think you would want to use an init only property for your example

    class Test {
        public string Test { get; init; }
    }

I'm not a C# expert though, and there seems to be many ways to do the same thing.


I don't use the init decorator myself but I would hazard a guess it's similar. Don't quote me on that though.

The point does stand though, outside of modifying properties I'm not sure what a "private" class itself achieves.


> I don't use the init decorator myself but I would hazard a guess it's similar.

Genuinely curious, why not? Seems to be less verbose. I don’t write C#s so I’m not sure of the downsides of any particular feature.




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

Search: