19 Replies
Just this constructor?
In C# 12 you can do
Otherwise, there's not really any better way to write such a small constructor
Shouldn't that just be:
Yeah it could
there's a slight difference, yours doesn't necessarily create a field
but for most cases they're interchangeable
It's unclear from the OP what
this.size
is intended to be...with the way people case things around here it could be a property 😄I like how in Kotlin you can do this:
Wish C# had that feature
So
size
would be a private field?No modifiers, alas, but that's what primary ctors are
Yeah, still pretty nice
So they're not object members
The compiler will generate
Oh, I see
The compiler creates storage for any primary constructors only when that parameter is accessed in the body of a member of your type. Otherwise, the primary constructor parameters aren't stored in the object. Primary constructor parameters aren't members of the class. For example, a primary constructor parameter namedparam
can't be accessed asthis.param
. Weird So they're not, but they also are Or the other way around
Yeah, if you just do
the compiler will generate
It's not like records, those actually generate properties and a bunch more code
But here in the method the parameter can't be used as
this.bar
, right?Let's see
Angius
REPL Result: Failure
Exception: CompilationErrorException
Compile: 453.784ms | Execution: 0.000ms | React with ❌ to remove this embed.
It seems no, it cannot
Angius
REPL Result: Success
Console Output
Compile: 413.586ms | Execution: 25.561ms | React with ❌ to remove this embed.
It's fine without
this
, though
Which, let's be honest, who ever uses this.
explicitlySome people do, but I'm not one of them