Reputation: 47
I would like to know if it is possible to know which constructor has been called to create an instance of an object. For Example:
public class Dog
{
public string Name;
public int Age;
public Dog(){}
public Dog(string n, int age)
{
this.Name = n;
this.Age = age;
}
public Dog(string n)
{
this.Name = n;
}
}
Now I create a class instance:
var dog = new Dog("pippo", 10);
Now (I think with reflection) I want to know from "var dog" which constructor i have used to create a Dog instance if the class has more then one, is it possible?
Thanks.
Upvotes: 1
Views: 1347
Reputation: 460208
No, it's not possible and also should be unnecessary to know which constructor was called. If you are in that constructor you know already where you are. If you are in the caling code you also know what constructor you have called.
You could store related informations in a variable. For example:
bool dogWithAge = true;
var dog = new Dog("pippo", 10);
// ....
if(dogWithAge)
{...}
else
{...}
If it's so important that you need to know whether the dog was created with an age or not you could also modify the class.
public class Dog{
public string Name { get; set; } // use public properties not fields
public int Age { get; set; } // use public properties not fields
//...
public bool IsAgeKnown { get; set; }
public Dog(string n, int age){
this.IsAgeKnown = true;
this.Name = n;
this.Age = age;
}
}
Now you can always check that property: if(dog.IsAgeKnown) ...
Another approach which works in this case: use a Nullable<int>
instead of an int
. Then you can use if(dog.Age.HasValue)
.
Upvotes: 3
Reputation: 2148
public enum UsedConstructor { Default, Name, NameAndAge };
public class Dog
{
UsedConstructor UsedConstructor { get; }
public string Name;
public int Age;
public Dog()
{
UsedConstructor = UsedConstructor.Default;
}
public Dog(string n, int age)
{
UsedConstructor = UsedConstructor.NameAndAge;
this.Name = n;
this.Age = age;
}
public Dog(string n)
{
UsedConstructor = UsedConstructor.Name;
this.Name = n;
}
Upvotes: 3
Reputation: 3511
If you want to know that in runtime, you can set a flag in this object. If in debug - set a breakpoint in both constructors.
public class Dog{
public string Name;
public int Age;
public string CreatedBy;
public Dog(){
this.CreatedBy = "parameterless constructor";
}
public Dog(string n, int age){
this.Name = n;
this.Age = age;
this.CreatedBy = "two parameters constructor";
}
public Dog(string n){
this.Name = n;
this.CreatedBy = "one parameter constructor";
}
}
You can use enum as well.
Upvotes: 0