Consider the following code:
The code
public class RecursiveConstructor
{
//When this constructor is called
public RecursiveConstructor():this(One(), Two())
{
Console.WriteLine("Constructor one. Basic.");
}
public RecursiveConstructor(int i, int j)
{
Console.WriteLine("Constructor two.");
Console.WriteLine("Total = " + (i+j));
}
public static int One()
{
return 1;
}
public static int Two()
{
return 2;
}
}
The calling method
public class RecursiveConstructorTest
{
public static void Main()
{
RecursiveConstructor recursiveConstructor = new RecursiveConstructor();
Console.ReadKey();
}
}
The Result
Constructor two.
Total = 3
Constructor one. Basic.
Why is the 2nd constructor run first?
I understand that in chained constructors we call the base class constructor first and then make our way back up the chain but when the constructor is held in the same class why do we still see this behaviour where the extra constructor is called first?
I would have thought that the most basic constructor contents would be executed first.
I think the compiler runs the safer scenario.
If you call another constructor here, there are chances that this other constructor is a prerequisite to your current constructor. This behaviour is consistent with the one exposed when calling base constructors, and is then to be expected.
When creating a new instance of a class, there is a chain of constructors that get called from the least specialized (the constructor of the object class) to the most specialized (the constructor of your current class).
The operator : allows you to explicitly add a constructor to this chain, so this order seems natural.
You gave the explanation yourself. It is almost the same way base constructors are called. Whenever calling a constructor in your signature, like
public RecursiveConstructor() : this(One(), Two())
or
public RecursiveConstructor() : base()
the constructor right after the : is called first.
It makes sense when you consider that there is always a hierarchical chain of constructor calls when initializing new objects. As you rightly say, the base classes constructor is called first.
The two forms of constructor initializer, : base(...), which is often implictly called, and : this(...) behave the same way.
So, in your case we have a chain:
Object()
then...
RecursiveConstructor(int i, int j)
then...
RecursiveConstructor()
It is calling constructor 1 first, but ctor1 is calling ctor2 before it hits the ctor1 code block, hence the output you see.
One way around this, but to retain the DRY behaviour would be to refactor the (int, int) overload:
//When this constructor is called
public RecursiveConstructor()
{
Console.WriteLine("Constructor one. Basic.");
Init(One(), Two());
}
public RecursiveConstructor(int i, int j)
{
Console.WriteLine("Ctor 2");
Init(i, j);
}
private void Init(int i, int j)
{
Console.WriteLine("Refactored");
Console.WriteLine("Total = " + (i+j));
}
Out of interest, chaining constructors this way is often referred to as 'delegating constructors'.
In Java, it is possible to place the call to the other constructor in the code block (e.g. see here), but it must be the first line in the block
Related
Firstly, sorry for my English. I hope i can explain my problem.
I have class like this
public class CarCommandExecutorBase
{
protected readonly ICarCommand CarCommand;
public CarCommandExecutorBase(ICarCommand carCommand)
{
CarCommand = carCommand;
}
}
Also i have class like this
public class CarStringCommandExecutor : CarCommandExecutorBase, IStringCommand
{
public CarStringCommandExecutor(Car car)
{
// this Constructor gives me an error.
}
public void ExecuteCommand(string commandObject)
{
}
}
Error message:
[![error][1]][1]
What's the reason and how can i fix it? Thanks.
Since the only constructor in CarCommandExecutorBase is defined like this
public CarCommandExecutorBase(ICarCommand carCommand)
{
CarCommand = carCommand;
}
you have to pass an ICarCommand when creating an instance of CarCommandExecutorBase.
You have to provide an ICarCommand through the constructor of CarStringCommandExecutor, because when instantiating a derived type the base constructor(s) also get called.
See this answer for more detailed information about this: https://stackoverflow.com/a/1882778/8450550
You could do something like this to solve this error:
public class CarStringCommandExecutor : CarCommandExecutorBase, IStringCommand
{
...
public CarStringCommandExecutor(Car car, ICarCommand carCommand)
: base(carCommand) // base() points to the constructor of the base class
{
...
}
or maybe this
public class CarStringCommandExecutor : CarCommandExecutorBase, IStringCommand
{
...
public CarStringCommandExecutor(Car car)
: base(null) // passing null but be aware of NullReferenceExceptions
{
...
}
or you add another constructor to CarCommandExecutorBase which expects no arguments:
public class CarCommandExecutorBase
{
protected readonly ICarCommand CarCommand;
public CarCommandExecutorBase(ICarCommand carCommand)
{
CarCommand = carCommand;
}
// mark this constructor as protected, so only deriving types can call it
protected CarCommandExecutorBase()
{
}
}
Which solution works best in your case is up to you.
One of the things that isn't immediately apparent, thanks to "compiler magic", about a C# class is that every class has a constructor
It needs to be this way because it's a rule that object construction happens in a tree; you construct some class Z which inherits from Y which inherits from X which inherits from object, and Z's cosntructor invokes Y's invokes X's invokes object's, then they finish, in order of object, X, Y, Z and you have your nicely constructed thing - every constructor on the way up the tree had its chance to do its init and ready the object for use (the part of it that each constructor was responsible for)
Even classes that don't seem to have constructors, have constructors:
class X {
}
If you don't provide a constructor, C# provides one for you. You never see it in your source code; just imagine that in between reading the file and compiling it, the compiler inserts it for you. It takes no parameters, has no code, and does nothing other than call its base:
class X {
X():base() { } //C# invisibly writes this for you
}
If you provide a constructor but don't write the base... bit, C# puts base() in for you behind the scenes (and it always calls the no-argument base()) but critically it doesn't provide an empty constructor if you provided one already
This means if you have a class like:
class X{
X(string message){
...
}
}
Your class X has a constructor, so C# won't provide the empty one, so now anything that tries to construct your class must provide a string message:
X x = new X("hello");
If you now inherit from X, you might do one of 3 things (with Y):
class Y:X{
}
You don't add a constructor, C# adds one, but it just dumbly calls base(), which doesn't work because there is no constructor in X that takes no args:
class Y:X{
Y():base() { }
}
You add a constructor but leave off the base bit. C# adds it, again just literally as base() - this also doesn't work for the same reason
class Y:X{
Y(int myArg) //c# adds base() in here for you
{
...
}
}
You add a constructor that includes a call to base and because you know your base class only has a constructor with a string arg, you pass one:
class Y:X{
Y(int myArg) : base("hello")
{
...
}
}
So you're in scenario 2, and you either need to:
Add a no-arg constructor to the base class so that c#'s auto-inserted stuff works or,
Add a call to base(...) with a suitable argument, to stop C# from putting a base() in
I've left out access modifiers from code in this answer for clarity of demonstrating the essential point. Whether a constructor is accessible or not can also have a bearing on all this, but I deemed it out of scope
On VS C# Express, I get this error when running the code below:
'myComponent.SettingsComponentAttributes' does not contain a
constructor that takes 1 arguments.
I have tried adding a constructor in the class itself but the same message applied to the new constructor:
public override void CreateAttributes()
{
m_attributes = new SettingsComponentAttributes(this);
}
public SettingsComponentAttributes(SettingsComponentAttributes obj)
{
}
Your class doesn't declare any constructors, therefore it's equivalent to having a single parameterless constructor:
public SettingsComponentAttributes()
{
}
You're trying to pass an argument (this) into the constructor - which isn't going to work. You'll need to either change your constructor call, or declare an appropriate constructor.
You should also look at the error message carefully and work out why you needed to ask on Stack Overflow. Which bit of the message wasn't clear to you? Revise that aspect of your C# knowledge. Understanding error messages is a very important part of being a good developer, and this one is fairly clear:
You're trying to use a constructor with 1 argument
No such constructor exists
Default constructors are parameterless, so if you want to create a constructor which accepts one argument you have to create it yourself
Something like this
public class SettingsComponentAttributes : GH_ComponentAttributes
{
public override void CreateAttributes()
{
m_attributes = new SettingsComponentAttributes(this);
}
public SettingsComponentAttributes(SettingsComponentAttributes obj)
{
// Do your fancy work here
}
}
You need to create a class constructor that takes 1 arguement, e.g.:
public SettingsComponentAttributes(SettingsComponentAttributes other)
{
// Initialise.
}
You haven't got a constructor that takes 1 argument
public SettingsComponentAttributes(int i)
If I have a class like this:
public class Foo
{
public IEnumerable<Bar> Bars { get; set; }
public Foo()
{
Bars = new List<Bar>();
}
}
At some stage I re-factor the class and add a secondary constructor which implements the first one like this:
public class Foo
{
public IEnumerable<Bar> Bars { get; set; }
// some more properties were added
public Foo()
{
Bars = new List<Bar>();
}
public Foo(string parameter): this()
{
.... some code here
}
}
I could have also written it similar to this:
public class Foo
{
public IEnumerable<Bar> Bars { get; set; }
// some more properties were added too
public Foo()
{
InitilizeFoo();
}
public Foo(string parameter)
{
InitilizeFoo();
.... some code here
}
private void InitializeFoo()
{
Bars = new List<Bar>();
}
}
Seeing both approaches work in this scenario, is there a benefit or drawback in using one over the other?
Is inheriting constrcutors more efficient and making that code execute faster or is there a drawback which I don't know about making the second implementation more efficient instead?
One of the key benefits in having one constructor call another constructor is that you can set read-only fields that way, you can't do that by calling a non-constructor method.
For example:
public class Foo
{
private readonly int myNumber;
public Foo() : this(42)
{
}
public Foo(int num)
{
myNumber = num;
}
}
Performance wise, it's probably no more or less efficient to call another constructor than to call another method, but it is more readable, in my opinion, for a constructor to call another constructor than to call a separate, private method whose only point is to be called by a constructor.
There could, of course, be situations when having a separate method makes sense, and it's certainly not "wrong" per se. Chaining constructors just reads better to many for most uses, and there is no negative performance impact.
UPDATE: I performed 10,000,000 iterations of each way (chained vs private initialization method) and the results were so close they were nearly indistinguishable:
Initializer Method took: 84 ms for 10,000,000 iterations, 8.4E-06 ms/each.
Chained Constructors took: 81 ms for 10,000,000 iterations, 8.1E-06 ms/each.
So really, performance-wise there is nearly no benefit either way. The main benefit is with chained constructors you can set readonly fields, and in most cases it is more readable.
Chaining constructors is a good way to enforce SRP and program flow. Hiding initialization code inside a standalone Initialize() function could make sense if there are other situations in the object lifecycle where you might also want to "Initialize" it; perhaps if you wanted to be able to quickly instantiate and lazy-initialize it. But if the only valid time in the lifecycle to execute that functionality is during instantiation, and initialization is a well-defined set of discrete steps that need to be taken in order, then chaining facilitates that.
The key is to reduce the amount of duplicate code. In this case, calling the base constructor from a parameterized constructor reduces the chances of adding a bug later on after forgetting to update both of them.
A benefit of having an Initialise() function is in case you would like to reset your object - you can simply call the init function again rather than delete & recreate the object.
I may get burned for saying this but I prefer using default parameters in this case:
public Foo(string parameter = null)
{
}
I've had cases where I had 10 - 15 optional parameters and having 15 different constructors wasn't an elegant solution in my opinion. I think default parameters were only reintroduced in the 4.0 framework though.
Is there a way to do so as it seems partial method must return void (I really don't understand this limitation but let it be) ?
Well, technically you can "return" a value from a partial method, but it has to be through a ref argument, so it's quite awkward:
partial void Foo(ref int result);
partial void Foo(ref int result)
{
result = 42;
}
public void Test()
{
int i = 0;
Foo(ref i);
// 'i' is 42.
}
In that example, the value of i won't change if Foo() is not implemented.
From MSDN:
Partial method declarations must begin with the contextual keyword partial and the method must return void.
Partial methods can have ref but not out parameters.
So the answer is no, you can't.
Perhaps if you explain a bit more about your situation (why you need to return a value, why the class is partial), we can provide a workaround.
You cannot return a value from a partial method.
Partial methods may or may not be implemented. If it were permitted to return a value from such a method, then what would the caller receive?
The reason for the restriction is this line from MSDN:
A partial class or struct may contain
a partial method. One part of the
class contains the signature of the
method. An optional implementation may
be defined in the same part or another
part. If the implementation is not
supplied, then the method and all
calls to the method are removed at
compile time. -- Emphasis Mine
If the method may not be implemented and can be removed. What would happen to its return value if the call is removed?
As to your question of a work around, that depends on what you are trying to do, but obviously you can't use a partial method.
Oh. Once I had to do this in a project of mine.
You can throw an exception in your method called ReturnValueException which you define as an exception that has an object property named ReturnedValue. Now you can call your method Foo() inside a try block and collect the results in the catch block.
No.. just kidding.
Don't do that. Ever.
Here's a technique relying on the fact that an extension method will be shadowed by a class method.
It's more involved and less clear than the ref parameter technique, so I'll use that instead.
Several shadowing mechanisms in C# could be used instead: using static vs. method, a parent class containing just the default behaviour vs. a new method, a method accepting a dummy object vs. a method with a more specific argument type etc.
The choice between the extension method or the class method when it is present is made at compile-time (that is, it doesn't use late binding). This can lead to some problems if your partial class is not sealed: if you override the customizable method with an implementation which is also customizable, you need to use a fresh interface and extension method
https://repl.it/#suzannesoy/WorthwhileSplendidBotany#main.cs
// On the auto-generated side:
interface IDefaultFoo { int DefaultFoo(); }
static class DefaultFoo {
public static int CustomFoo(this IDefaultFoo o) => o.DefaultFoo();
}
partial class PartialClass : IDefaultFoo {
int IDefaultFoo.DefaultFoo() => 42;
// mark as virtual if you want to override in subclasses too.
public virtual int Foo() => this.CustomFoo();
}
// On the user side:
partial class PartialClass {
// Define this method only if you want to change
// the default implementation of Foo.
public int CustomFoo() => 123;
}
// In subclasses use override on the Foo method as usual
class SubClass1 : PartialClass {
public new int CustomFoo() => 666; // This is not used
public override int Foo() => 999; // Use this instead
}
// If you also want to override in the subclass with a method which
// is also customizable, i.e. to provide a new default behaviour in
// the partial subclass that could also be customized, you'll need
// to add a new interface etc. otherwise the CustomFoo from the
// parent class would be called because it still shadows the
// extension method.
interface IDefaultFooSub2 { int DefaultFoo(); }
static class DefaultFooSub2 {
public static int CustomFooSub2(this IDefaultFooSub2 o) => o.DefaultFoo();
}
partial class SubClass2 : PartialClass, IDefaultFooSub2 {
int IDefaultFooSub2.DefaultFoo() => 1000000;
public override int Foo() => this.CustomFooSub2();
}
class MainClass {
public static void Main (string[] args) {
System.Console.WriteLine(new PartialClass().Foo()); // 123
System.Console.WriteLine(new SubClass1().Foo()); // 999
System.Console.WriteLine(new SubClass2().Foo()); // 1000000
System.Console.WriteLine(((PartialClass)new SubClass2()).Foo()); // 1000000
}
}
What is the need of private constructor in C#?
I got it as a question for a C# test.
For example if you have a class that should only be created through factory methods. Or if you have overloads of the constructor, and some of them should only be used by the other constructors. Probably other reasons as well =)
If you know some design pattern, it's obvious: a class could create a new instance of itself internally, and not let others do it.
An example in Java (I don't know C# well enough, sorry) with a singleton-class:
class Meh
{
private Meh() { }
private static Meh theMeh = new Meh();
public static Meh getInstance() { return theMeh; }
}
Whenever you want to prevent direct instantiation of a class from outside of it, you'll use a private constructor. For example, prior to C# 2.0 which introduced static classes, you used a private constructor to accomplish roughly the same thing:
sealed class StaticClass {
private StaticClass() {
}
public static void DoSomething() {
}
}
When you want to prevent the users of your class from instantiating the class directly. Some common cases are:
Classes containing only static methods
Singletons
I can can recall few usages for it:
You could use it from a static factory method inside the same class
You could do some common work inside it and then call it from other contructure
You could use it to prevent the runtime from adding an empty contructure automatically
It could be used (although private) from some mocking and ORM tools (like nhibernate)
For example when you provide factory methods to control instantiation...
public class Test(){
private Test(){
}
void DoSomething(){
// instance method
}
public static Test CreateCoolTest(){
return new Test();
}
}
Private constructors are used to prevent the creation of instances of a class when there are no instance fields or methods, such as the Math class, or when a method is called to obtain an instance of a class. If all the methods in the class are static, consider making the entire class static. For more information see Static Classes and Static Class Members.
class NLog
{
// Private Constructor:
private NLog() { }
public static double e = System.Math.E; //2.71828...
}
The following is an example of a class using a private constructor.
public class Counter
{
private Counter() { }
public static int currentCount;
public static int IncrementCount()
{
return ++currentCount;
}
}
class TestCounter
{
static void Main()
{
// If you uncomment the following statement, it will generate
// an error because the constructor is inaccessible:
// Counter aCounter = new Counter(); // Error
Counter.currentCount = 100;
Counter.IncrementCount();
System.Console.WriteLine("New count: {0}", Counter.currentCount);
}
}
While this link is related to java, I think it should help you understand the reason why as the idea is pretty much the same.
Private constructors prevent a class from being explicitly instantiated by callers. There are some common cases where a private constructor can be useful:
classes containing only static utility methods
classes containing only constants
type safe enumerations
singletons
You can use it with inheritance in a case where the arguments to the constructor for the base class are of different types to those of the child classes constructor but you still need the functionality of the base class in the child class eg. protected methods.
Generally though this should be avoided wherever possible as this is a bad form of inheritance to be using.
I'm late to the game, but reading through all the other answers, I don't see this usage mentioned:
I use private constructors in scenarios where I have multiple (public) constructors, and they all have some code in common. With constructor chaining, the code becomes really neat and DRY.
Remember, the private readonly variables can only be set in constructors, so I can't use a regular method.
Example:
public class MyClass
{
private readonly int _a;
private readonly int _b;
private readonly string _x;
public MyClass(int a, int b, string x)
: this(x)
{
_a = a;
_b = b;
}
public MyClass()
: this("(not set)")
{
// Nothing set here...
}
private MyClass(string x)
{
_x = x;
}
}
Basically you use private constructors when you are following a singleton design pattern. In this case, you have a static method defined inside the class that internally calls the private constructor.
So to create the instance of the class for the first time, the user calls the classname.static_method_name. In this method, since the class's object doesn't yet exist, the static method internally calls the private constructor and returns the class's instance.
If the class's instance already exists, then the static method simply returns the instance to the calling method.
And of course you can use private constructor to prevent subclassing.