public Butler(IWeapon weapon): this(weapon, new Communicate())
{}
What does this(weapon, new Communicate()) mean?
It calls another constructor on the same type, passing in the weapon that was passed to this constructor, and a new Communicate object. I assume there is also something like:
// might actually be private
public Butler(IWeapon weapon, Communicate communicate) {...}
This approach is useful by allowing you to have multiple constructors, but only put the code in the most complex one. All the other constructors just pass the arguments (or defaults, as necessary) to the chosen constructor.
The chained constructor gets invoked before the body of the constructor that has the : this(...)
It calls a constructor in the same class but with different parameters, for example:
public class Test
{
public Test() : this("Richard")
{
}
public Test(string name)
{
}
}
It means Butler extends an instance of the current class where the weapon object passed as the argument, and a new instance of the Communicate object are passed to the class constructor.
it is calling another constructor with the signature Butler(IWeapon, ICommunicate).
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
We all know that we cannot create object of class having private constructor. So the question arises is how many instances of this class can be created .Please find a sample code below.
public class Test
{
public int val ;
private Test(int sent)
{
val=val +sent;
}
public static void Callme(int GetVal)
{
Test obj=new Test(GetVal);
Console.WriteLine(obj.val);
}
}
public class Program
{
public static void Main()
{
Test.Callme(10);
//Console.WriteLine(Test.val);
Test.Callme(20);
//Console.WriteLine(Test.val);
}
}
As per what I know It should create 2 object of the class. Need help understanding this.
We all know that we cannot create object of class having private constructor.
Well, that's not accurate. You can create an object (instance) of a class having only private constructors by using static members of that class, just like in the code in the question.
What you can't do is create an instances of that class from anywhere else in the code.
how many instances of this class can be created
In your code sample there are two instances of class Test.
I think what might be confusing you is you expected the second Console.WriteLine to print 30, but it printed 20. That is because public int val ; is an instance member. If it was a static member, than it would have printed 30
Maybe something like this is what you're looking for:
public static Test Callme(int GetVal)
{
Test obj = new Test(GetVal);
Console.WriteLine(obj.val);
return obj;
}
And then create new instances like:
Test test1 = Test.Callme(10);
Test test2 = Test.Callme(20);
This way you can easily access the members of each instance. E.g. test1.val
Callme method is a static method. Static methods does not require an objects instance to be called upon. They don't have the this (keyword) reference and can be called directly on the class. In your situation Test.CallMe(someValue). Note that there is no object instance involved here.
If CallMe was NOT a static method you would have needed an instance/object to call it. For example
Test ob = new Test();
ob.CallMe(someValue);
What your example illustrates is the use of private fields/methods.
When a method like the constructor or a filed is marked with the private keyword that method/field can only be called/accessed from within the declaring class.
This means that CallMe can access the constructor because CallMe is a member of the class and the constructor is a member of the class thus they both can access each other.
When a class has only one constructor and that constructor is private it effectively means that an instance of the class can only be created from within the class.
So in current example CallMe creates an instance of the class each time it's called.
If you call CallMe 2 times you'll create 2 instances of the class.
Because the method Callme is static it is instantiated by the system at some point before it is used and then remains in memory for future calls. There is only one copy of a static memeber of a class ever created regardless of how many instances of the class are created.
This question already has answers here:
Call one constructor from another
(13 answers)
Closed 9 years ago.
I saw this code block when i was trying build something with APN. Could someone explain me what does "this" statements do there ?
public ApplePushService(IPushChannelFactory pushChannelFactory, ApplePushChannelSettings channelSettings)
: this(pushChannelFactory, channelSettings, default(IPushServiceSettings))
Is it like default values of those arguments ?
this calls the overloaded constructor for the ApplePushService class with the specified parameters.
For example
// Set a default value for arg2 without having to call that constructor
public class A(int arg1) : this(arg1, 1)
{
}
public class A(int arg1, int arg2)
{
}
This lets you call one constructor that can invoke another.
Sure - that chains one constructor onto another. There are two forms - this to chain onto another constructor in the same class, and base to chain to another constructor in the base class. The body of the constructor you're chaining to executes, and then your constructor body executes. (Of course, the other constructor may chain onto another one first.)
If you don't specify anything, it automatically chains to a parameterless constructor in the base class. So:
public Foo(int x)
{
// Presumably use x here
}
is equivalent to
public Foo(int x) : base()
{
// Presumably use x here
}
Note that instance variable initializers are executed before the other constructor is called.
Surprisingly, the C# compiler doesn't detect if you end up with mutual recursion - so this code is valid, but will end up with a stack overflow:
public class Broken
{
public Broken() : this("Whoops")
{
}
public Broken(string error) : this()
{
}
}
(It does prevent you chaining onto the exact same constructor signature, however.)
For more details, see my article on constructor chaining.
That is calling another constructor in that case, the : this(...) is used to call another constructor in that class.
For example:
public ClassName() : this("abc") { }
public ClassName(string name) { }
EDIT:
Is it like default values of those arguments ?
It an overload you can delegate it's full logic in one place and call from the rest of the constructors with default values.
this keyword can be used in these contexts:
Call other constructors.
Passing the current object as a parameter.
Refer to instance methods or fields.
Having read the access modifiers in C# progamming tutorial, I come to conclusion that defining a method public is enough for it to be "seen" from another Form of the same namespace.
However, in practise whenever I tried to implement this, I also had to define the method as static in order for it to be referenced from other Forms of the same namespace.
Am I loosing something?
I am doing somethning wrong?
For a public static method, you don't need a reference to an object. The method is static and can be accessed on class level.
If you can't access a public method, then you need a reference to the object, then you can.
public class AClass
{
public void DoSomething() {}
public static void DoSomethingElse() {}
}
You can use them as follows:
AClass.DoSomethingElse(); // no object reference required
AClass.DoSomething(); // will give compiler error, since you have no object reference.
var anObject = new AClass();
anObject.DoSomething(); // will work fine.
anObject.DoSomethingElse(); // compile error (thx hvd).
public static method do not need object instance, they can be used without creating any instance of the class
ClassName.MyStaticPublicMethodName()
where as public (non-static) method require an Instance of the Class, public (non-static) method in general helps you to work with the data member (field) of the object.
To use a non-static public method you need to create instance of the class
ClassName obj = new ClassName();
obj.MyPublicMethod();
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)