Primary constructors in C# vnext -


the language feature implementation status brought attention via c# chat. have couple of questions of features not covered in this existing question.

some of new features obvious such getter-only auto-properties

public int y { get; } = y; 

... awesome.

but others not clear on...


primary constructors

class point(int x, int y) { … } 

it may gap in knowledge, haven't come across term "primary constructor" before, some research seems suggest shortcut defining following

class point {     private int x;     private int y;      public point(int x, int y)     {         this.x = x;         this.y = y;     } } 
  • is correct interpretation?
  • does mean can still constructor overloads (the term "primary" implies so)?
  • can refer these implicit backing fields in other constructors/methods?

  • is correct interpretation?

almost, not exactly. default, primary constructor parameters not captured fields; are, however, accessible in instance member initializers (and there), can explicitly initialize fields or properties them:

class point(int x, int y) {     public int x { get; } = x;     public int y { get; } = y; } 

(note in case, backing fields are created, properties, not constructor parameters)

but can declare parameters access modifiers, in case captured fields, , accessible instance members:

class point(public readonly int x, public readonly int y) { } 

(as can see, can specify other modifiers fields, readonly)

  • does mean can still constructor overloads (the term "primary" implies so)?

yes, can have other, non-primary constructors. however, they're required call primary constructor, usual : this(...) syntax.

  • can refer these implicit backing fields in other constructors/methods?

as mentioned above, there no implicit backing fields; backing field created if explicitly specify access modifier on primary constructor parameter.


edit: feature has been withdrawn , won't in c# 6 (probably in c# 7, in different form)


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -