Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: if a class has two constructors, what is the best way for these constructors to share some code? [duplicate]

Tags:

c#

constructor

C# in VS2005: if a class has two constructors, what is the best way for these constructors to share some code?

eg. How could I avoid having the x = 5 and y = 10 lines in both constructors for the following:

public class MyObject {  int x; int y; int z;  public MyObject() {     x = 5;     y = 10; }  public MyObject(int setZ) {     x = 5;     y = 10;     z = setZ; } 
like image 760
CJ7 Avatar asked Jun 30 '10 02:06

CJ7


1 Answers

Just chain to the common constructor...

public MyObject(int setZ)   : this() {   z = setZ; } 
like image 50
Rob Avatar answered Sep 26 '22 00:09

Rob