-1

You can pass an expression into another constructor as follows:

using System;

public class Wine{

public decimal Price;
public int Year;
public Wine(decimal price){Price = price;}

public Wine(decimal price, int year) : this(price) {Year = year;}

public Wine(decimal price, DateTime year) : this (price, year.Year) {}

}

In the book - "Any methods that you call on it are likely to fail. It can, however, call static methods.

My question is "Why"?

Hafiz
  • 21
  • 4
  • 2
    *Any methods that you call on **it** are likely to fail.* -> define *it*. – Peter Bons Aug 25 '21 at 08:12
  • 1
    You should ask the author. See also [this](https://stackoverflow.com/questions/4604981/methods-in-constructors-bad). – Sweeper Aug 25 '21 at 08:12
  • when you wish to re-use certain code blocks, you can use this pattern of constructor overloading, see for example - [link](https://stackoverflow.com/questions/5555715/c-sharp-constructors-overloading) – GuyKorol Aug 25 '21 at 08:30
  • Maybe (?) it refers to calling methods inside the constructors, and meaning that calling static methods should be fine. Maybe... – Gec Aug 25 '21 at 08:37
  • 1
    Which book and page/chapter are you refering to? – TaW Aug 25 '21 at 09:11

1 Answers1

2

The statement this(price) calls an overloaded constructor initializer.

With that in mind, this is how I read the quote:

Any [instance] methods [belonging to the constructed class] that you call [in the constructor initializer] are likely to fail. [Constructor initializers] can, however, call static methods.

Why is this the case?

  1. Instance methods are likely to fail because they rely on the object's internal state, but the object hasn't been constructed yet. (Constructor initializers run before the body of the constructor.)
  2. Static methods are okay because they don't have a reference to the not-yet-constructed object. (They don't have access to its internal state - there's no this in static methods.)
Spencer Bench
  • 647
  • 4
  • 7