3

When chaining constructors, in C#, how can I easily tell whether or not the constructor was called directly, or was called by another constructor using this?

public Test() : this(string.Empty, string.Empty) {}
public Test(string helloworld) : this(helloworld, string.Empty){}
public Test(string helloworld, string goodbyeworld)
{
   //do work
}
casperOne
  • 73,706
  • 19
  • 184
  • 253
dbobrowski
  • 846
  • 2
  • 9
  • 18
  • 4
    Out of curiosity, why would you need to know this? – Phil Klein Dec 15 '11 at 13:49
  • Add an example. Don't understand what you mean with "master" – jgauffin Dec 15 '11 at 13:49
  • 13
    If you need this, you're doing it wrong – Robert Levy Dec 15 '11 at 13:49
  • Yes - I confused the order of calls. I have no issue. My master constructor is called first, then the other. I thought this was the other way around. This is a non issue...flagging it. – dbobrowski Dec 15 '11 at 14:04
  • see the constructors? The final one on the code sample above... There are 3 constructors above. 1, 2, and 3. 3 comes after 2, 2 after 1. The third constructor above is the final constructor in order of appearance on the code sample above. To elaborate on the example more: If I had a line of pigs, 3 pigs, the final pig in the line would be the last pig, the 3rd pig in the line of pigs. – dbobrowski Dec 15 '11 at 14:09
  • If you want to know whether a particular constructor for your type is being called by another constructor of your same type, define a private constructor overload (possibly with an extra dummy parameter) and call it from your other constructors. If you want to know whether a particular constructor is being called from a derived-class constructor versus being called directly, check the type of `this` within the constructor. – supercat May 29 '12 at 20:08

2 Answers2

2

If for some reason you really NEED to do this (and you pretty much never need to) this can be accomplished by making your "Master" constructor private or protected and adding another argument that indicates which other constructor was used.

I realize this is sort of a ridiculous answer but the problem is kind of ridiculous as well.

M.Babcock
  • 18,753
  • 6
  • 54
  • 84
0

It isn't perfectly accurate, but you can check the call stack. See this question for more info

How can I find the method that called the current method?

Community
  • 1
  • 1
Jonathan Allen
  • 68,373
  • 70
  • 259
  • 447