-2

Usually a Constructor in C# is repeating a lot of assignements to symbols that already exist.

As an example:

 class P{
    int x;
    int y;
    int z;
    P(int x,int y,int z,...)
     {
       this.x=x;
       this.y=y;
      this.z=z;
      /...
    }
 }

Is there a way to default assign constructor inputs to fields of the same name. It makes no sense to reimplement this one-one map for every class.

David Basarab
  • 72,212
  • 42
  • 129
  • 156
Alex
  • 1
  • 4
    Possible duplicate of [Shortcut for creating constructor with variables (C# VS2010)](http://stackoverflow.com/questions/8893979/shortcut-for-creating-constructor-with-variables-c-vs2010) – Camilo Terevinto Jan 08 '17 at 20:40

2 Answers2

0

Currently it's not possible.

But there is a feature in C# backlog called Records. Though I'm not sure if we'll see it in C# 7. Record types allow one-line definition of classes with set of properties which automatically will be assigned with constructor arguments. E.g.

public class Point(int X, int Y);

Which is same as

public class Point
{
    public int X { get; }
    public int Y { get; }

    public Point(int x, int y)
    {
       X = x;
       Y = y;
    }

    // plus Equals, GetHashCode, With
}
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
0

Not in the way you are thinking (if I understand you correctly). The names of the parameters to the constructor and the names of the fields/properties are really just convenient labels for humans. A class should be independent and encapsulate it's state. Even allowing an compiler option to make external (passed in) names equate the internal ones confuses that concept.

You can do things like this:

    public class foo {
    public int X { get; set; }
    public string Y { get { return X.ToString(); } }
    public double Z { get; private set; }
    private foo(int x) { X = x; }
    public foo(int x, string y, double z = 1.0): this(x) {
        Z = z;
        }
    }

Where a public constructor uses a private constructor (or other public constructor) to do some of the work (as the last foo constructor does). And you use optional parameters (as the seeing of z in the last foo constructor shows).

Dweeberly
  • 4,668
  • 2
  • 22
  • 41