How to call base constructor inside constructor depending on parametres? For example:
public SomeConstructor (){
if(SomeParameter == "something") //here call base("something");
else //here call base("something else")
}
in my example
SomeParameter
could be for example local computer name.
To explain what am i doing, i want to determine constructor depending on computer name. I am working on MVC project, and i still forget change name of connection string when i'm publishing project on the server. so, i want to specify if computer name == my computer name, then call
:base("DefaultConnection")
otherwise, call for example
:base("ServerConnectionString")
To call the parameterized constructor of base class inside the parameterized constructor of sub class, we have to mention it explicitly. The parameterized constructor of base class cannot be called in default constructor of sub class, it should be called in the parameterized constructor of sub class.
Most of the time the runtime will call the base class default constructor for you when you create your derived class object, so you do not need to call "base()". By default, a derived class when instantiated will always IMPLICITLY call the base class default constructor.
A derived Java class can call a constructor in its base class using the super keyword. In fact, a constructor in the derived class must call the super's constructor unless default constructors are in place for both classes.
To call one constructor from another within the same class (for the same object instance), C# uses a colon followed by the this keyword, followed by the parameter list on the callee constructor's declaration. In this case, the constructor that takes all three parameters calls the constructor that takes two parameters.
You can't do that way, you can only call as in your latter examples, and even then, both your examples are passing a string and not changing the parameter type, so it seems senseless this way (they're not even different constructors you're calling). You could get away with calling the constructor in the conventional way, and making sure the provided value is the valid one prior to that.
As an off the cuff example, consider the following:
public SomeConstructor()
: base(Configuration.ConnectionString) {
}
public static Configuration {
public static string ConnectionString {
get {
/* some logic to determine the appropriate value */
#if DEBUG
return ConfigurationManager.ConnectionStrings["DebugConnectionString"];
#else
return ConfigurationManager.ConnectionStrings["ReleaseConnectionString"];
#endif
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With