I want to do something like this
public class Class1
{
public Class1()
{
}
public Class1(int a)
{
}
}
public class Class2 :Class1
{
public Class2(int a)
{
}
public Class2(): base(2)
{
this(2); // new Class2(2);
}
}
I know this can't be achieved in Java (can use one between (super or this) in the first line)
But somehow I am in need of this kind of work how to achieve that? Means calling the base class's parameterised and derived class's parameterised constructor in default constructor of derived class.
MSDN article on constructors is pretty good. Here are some relevant bits:
A constructor can use the base keyword
to call the constructor of a base
class.
....
A constructor can invoke another
constructor in the same object using
the this keyword. Like base, this can
be used with or without parameters,
and any parameters in the constructor
are available as parameters to this,
or as part of an expression.
This should work:
public class Class1
{
public Class1()
{
}
public Class1(int a)
{
}
}
public class Class2 :Class1
{
public Class2(int a) : base(a)
{
}
public Class2(): this(2)
{
}
}
Igor's answer is a fine example of how you should write the constructors in this situation. To address the more general case of your final sentence: you can't chain to more than one constructor. You can't call a base constructor and another constructor in the current class.
There are two typical patterns for overloaded constructor. In the first pattern, the set of overloads of the derived class roughly matches the set of overloads for the base class - you try to make the derived class feel like it's inherited the constructors, effectively. (Constructors themselves aren't inherited, but if you provide the same signatures then it feels like it to the caller.) This is typically the case when your derived class doesn't need additional information. Of course each constructor can have extra parameters, and only pass a subset up to the base constructor, but that can start to get complicated.
In the second pattern, you have several constructors in the derived class each of which calls a "master" constructor in the same (derived) class. This master constructor has the most parameters, as it needs to be able to handle everything specified by any of the other constructors. Sometimes the master constructor should be private, if some combinations wouldn't make sense, but are convenient to specify in one place when you know you can only reach the code via a sensible public constructor. In this case, only that "master" constructor chains directly to the base class constructor. This is typically used when the derived class has several additional pieces of information beyond what the base class needs.
There are hybrids of this pattern where you have multiple masters with "groups" of overloads calling the masters... but I'd advise you to try to keep it simple where possible. Also consider the possibility of providing static factory methods instead of constructors - that can end up making for more readable code as you can name the methods by their purpose/parameters - see TimeSpan.FromMinutes for example.
Thats impossible in both languages (for a good reason). Otherwise you would call the base-constructors multiple times due to the implicit base call if theres no explicit base or this. This could lead to unwanted behaviour.
Write multiple constructors, and one Init() method
Within each constructor, you can write whatever code you need to execute before passing it to the Init method.
Related
I have an interface IPopUp:
public interface IPopUp
{
bool IsCancelable {get;}
void Show();
void Close();
Action MainAction{ get; }
Action CancelAction{ get; }
}
I have several implementations for it: IfoPopUp, ErrorPopUp, and LoadingPopUp
I am creating the instances of the PopUps with a PopUpManager instance
public class PopUpManager
{
public void ShowPopUp<T>(string texto) where T:IPopUp
{
ShowPopup (()=>(IPopUp)Activator.CreateInstance (typeof(T)));
}
public void ShowPopUp<T>(string texto,Action mainAction)where T:IPopUp
{
ShowPopup (()=>(IPopUp)Activator.CreateInstance (typeof(T), mainAction));
}
public void ShowPopUp<T>(string texto,Action mainAction,Action cancelAction)where T:IPopUp
{
ShowPopup (()=>(IPopUp)Activator.CreateInstance (typeof(T), mainAction, cancelAction));
}
private void ShowPopup(Func<IPopUp> factoryFunc)
{
if (PopUpShowed != null) {
PopUpShowed.Close ();
}
IPopUp popUp = factoryFunc ();
popUp.Show ();
}
}
I don't know how can I force the IPopUp implementations to implement the 3 types of constructor I am using in the PopUpManager.
Abstract class won't work since it can force constructors...
Any ideas?
You have already found a nice solution to your question. Here some additional insights about forcing a class to implement certain constructors.
Can it be done with an interface ?
The C# language specification 5.0 defines in chapter 13 what an interface is:
An interface defines a contract. A class or struct that implements an
interface must adhere to its contract. An interface may inherit from
multiple base interfaces, and a class or struct may implement multiple
interfaces. Interfaces can contain methods, properties, events, and
indexers. The interface itself does not provide implementations for
the members that it defines. The interface merely specifies the
members that must be supplied by classes or structs that implement the
interface.
Instance constructors are not methods and can't be part of an interface. This is explicitly reminded in 13.2:
An interface cannot contain constants, fields, operators, instance
constructors, destructors, or types, nor can an interface contain
static members of any kind.
There are plenty of reasons that justify this language design choice, and you can find some additional explanations on SO. Note also that other languages have similar constraints. Java for example states that "Interfaces may not be directly instantiated."
Can it be done with an abstract class ?
The C# language specification says in section 10.1.1.1. that:
The abstract modifier is used to indicate that a class is incomplete
and that it is intended to be used only as a base class. (...) An abstract class cannot be instantiated directly, and it is a compile-time error to use the new operator on an abstract class.
Long story short, if you would define three different constructors in an abstract class, the derived classes would have to invoke one of these constructors, but without giving any constraint on their own constructors. Note that this logic also applies to C++ or Java.
The link of the abstract class with its derived classes is like the link between a Shape and the Square, Rectangle and Circle that implement the Shape: the construction paramters for a Rectangle can be very different from the construction parameters of a Circle, so that the Shape can't put constraints on the constructor of its children.
Can it be done with a combination ?
You want the PopupManager to instantiate an IPopUp that has certain properties. Unfortunately, you can't instantiate directly an IPopUp in a safe fashion (Activator.CreateInstance() might trigger an exception).
To make it safe, you could very well force IPopUp to require a setter for MainAction and CancelAction, and add a constructor constraint (e.g. where T:IPopUp, new()) to make sure that an instance can be created without surprise, and the object altered to fit the needs.
But in some case parameters need to be provided at construction. In this case you could consider using the builder pattern or the factory method as you've chosen. Note that in languages that allow interfaces with static members, you could even make three static factory methods mandatory in the IPopUp interface.
I end up by refactoring the class PopUpManager, so it needs a factory delegate to generate the PopUp.
Is much clear, and the responsibility of instantiating PopUps is from the caller that have much sense.
public void ShowPopUp(Func<IPopUp> factoryFuncPopUp)
{
if (PopUpShowed != null) {
PopUpShowed.Close ();
}
IPopUp popUp = factoryFuncPopUp();
popUp.Show ();
}
Anyway I am interested in knowing which approach is best to force a class to implements some constructor.
I had a similar problem. In my case, classes with a specific attribute [SpecialAttribute] were required to have a parameterless constructor.
I added a test to be run on our CI server after each build, where classes with that attribute are searched for, and then Activator.CreateInstance is called. In case of failures due to MissingMethodExceptions, that test "fails" and shows the classes with missing parameterless constructors.
That is not perfect, as the code does still compile. But a failed automated test with a clear message is an important step forward.
public class ParentBaseClass
{
public ParentBaseClass()
{
// Parameter less constructor
}
public ParentBaseClass(string type)
{
// single parameter constructor
}
public ParentBaseClass(Entity model)
{
// entity type constructor
}
public ParentBaseClass(string type, bool IsNewEntity)
{
// two parameter constructor
}
public ParentBaseClass(string type, bool IsNewEntity, Entity model)
{
// three parameter constructor
}
}
public class ChildClassFirst : ParentBaseClass
{
public ChildClassFirst() : base("Customer", false)
{
// implementation of 4th constructor having string, bool parameters.
}
}
in child class I implemented only one constructor of parent class having two parameters. why there no need to implement other constructor? can anyone explain me? please consider other constructor may have MVC Model class or other entity class of dbContext.
Every child class calls it's base class constructor, if there is a parameter-less constructor and we haven't implemented any parameter based constructor in it, the parameter-less is automatically called, but like in your case you are specifying which constructor to be used when ChildClassFirst is instantiated, so now the calling code has only access to this parameter-less constructor to instantiate an object of ChildClassFirst which in turn will instantiate the parent class object using the parameter based constructor which is called using base().
In short, Child class only needs to specify one base class construction which would be called during instantiation of child class, and when there is none specified the default would be parameter-less constructor which would get called, but remember the parameter-less only exists if we have no parameterized constructor specified in the class.
Abstract classes are designed for inheritance by other classes, usually more than one. Different derived classes may need to construct their abstract base class in slightly different ways. Hence, an abstract class can supply different constructors for different derived classes.
Non-abstract derived classes, on the other hand, are designed to be instantiated by the class users. User construction needs may be completely different from the needs of the class itself, so derived classes provide their own constructors.
Therefore, the two sets of constructors are completely independent of each other: they serve different needs. Derived classes can provide more or fewer constructors, and the signatures of their constructors may be similar or completely different. This is exactly the case in your code: ChildClassFirst provides a parameterless constructor, while its abstract base class provides two constructors with different sets of parameters. As long as you provide any constructor in the derived class, C# compiler is fine with your code.
Is there a way of forcing a (child) class to have constructors with particular signatures or particular static methods in C# or Java?
You can't obviously use interfaces for this, and I know that it will have a limited usage. One instance in which I do find it useful is when you want to enforce some design guideline, for example:
Exceptions
They should all have the four canonical constructors, but there is no way to enforce it. You have to rely on a tool like FxCop (C# case) to catch these.
Operators
There is no contract that specifies that two classes can be summed (with operator+ in C#)
Is there any design pattern to work around this limitation?
What construct could be added to the language to overcome this limitation in future versions of C# or Java?
Using generics you can force a type argument to have a parameterless constructor - but that's about the limit of it.
Other than in generics, it would be tricky to actually use these restrictions even if they existed, but it could sometimes be useful for type parameters/arguments. Allowing static members in interfaces (or possibly static interfaces) could likewise help with the "generic numeric operator" issue.
I wrote about this a little while ago when facing a similar problem.
Not enforced at compile-time, but I have spent a lot of time looking at similar issues; a generic-enabled maths library, and an efficient (non-default) ctor API are both avaiable in MiscUtil. However, these are only checked at first-usage at runtime. In reality this isn't a big problem - your unit tests should find any missing operator / ctor very quickly. But it works, and very quickly...
You could use the Factory pattern.
interface Fruit{}
interface FruitFactory<F extends Fruit>{
F newFruit(String color,double weight);
Cocktail mixFruits(F f1,F f2);
}
You could then create classes for any type of Fruit
class Apple implements Fruit{}
class AppleFactory implements FruitFactory<Apple>{
public Apple newFruit(String color, double weight){
// create an instance
}
public Cocktail mixFruits(Apple f1,Apple f2){
// implementation
}
}
This does not enforce that you can't create instance in another way than by using the Factory but at least you can specify which methods you would request from a Factory.
Force Constructors
You can't. The closest that you can come is make the default constructor private and then provide a constructor that has parameters. But it still has loopholes.
class Base
{
private Base() { }
public Base(int x) {}
}
class Derived : Base
{
//public Derived() { } won't compile because Base() is private
public Derived(int x) :base(x) {}
public Derived() : base (0) {} // still works because you are giving a value to base
}
The problem in the language is that static methods are really second class citizens (A constructor is also a kind of static method, because you don't need an instance to start with).
Static methods are just global methods with a namespace, they don't really "belong" to the class they are defined in (OK, they have access to private (static) methods in the class, but that's about it).
The problem on the compiler level is that without a class instance you don't have a virtual function table, which means you cannot use all the inheritance and polymorphism stuff.
I think one could make it work by adding a global/static virtual table for each class but if it hasn't been done yet, there's probably a good reason for it.
Here is I would solve it if I were a language designer.
Allow interfaces to include static methods, operators and constructors.
interface IFoo
{
IFoo(int gottaHaveThis);
static Bar();
}
interface ISummable
{
operator+(ISummable a, ISummable b);
}
Don't allow the corresponding new IFoo(someInt) or IFoo.Bar()
Allow constructors to be inherited (just like static methods).
class Foo: IFoo
{
Foo(int gottaHaveThis) {};
static Bar() {};
}
class SonOfFoo: Foo
{
// SonOfFoo(int gottaHaveThis): base(gottaHaveThis); is implicitly defined
}
class DaughterOfFoo: Foo
{
DaughhterOfFoo (int gottaHaveThis) {};
}
Allow the programmer to cast to interfaces and check, if necessary, at run time if the cast is semantically valid even if the class does not specify explicitly.
ISummable PassedFirstGrade = (ISummable) 10;
Unfortunately you can't in C#. Here is a punch at it though:
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Foo.Instance.GetHelloWorld());
Console.ReadLine();
}
}
public class Foo : FooStaticContract<FooFactory>
{
public Foo() // Non-static ctor.
{
}
internal Foo(bool st) // Overloaded, parameter not used.
{
}
public override string GetHelloWorld()
{
return "Hello World";
}
}
public class FooFactory : IStaticContractFactory<Foo>
{
#region StaticContractFactory<Foo> Members
public Foo CreateInstance()
{
return new Foo(true); // Call static ctor.
}
#endregion
}
public interface IStaticContractFactory<T>
{
T CreateInstance();
}
public abstract class StaticContract<T, Factory>
where Factory : IStaticContractFactory<T>, new()
where T : class
{
private static Factory _factory = new Factory();
private static T _instance;
/// <summary>
/// Gets an instance of this class.
/// </summary>
public static T Instance
{
get
{
// Scary.
if (Interlocked.CompareExchange(ref _instance, null, null) == null)
{
T instance = _factory.CreateInstance();
Interlocked.CompareExchange(ref _instance, instance, null);
}
return _instance;
}
}
}
public abstract class FooStaticContract<Factory>
: StaticContract<Foo, Factory>
where Factory : IStaticContractFactory<Foo>, new()
{
public abstract string GetHelloWorld();
}
Well, I know from the wording of your question you are looking for compile-time enforcement. Unless someone else has a brilliant suggestion/hack that will allow you to do this the way you are implying the compiler should, I would suggest that you could write a custom MSbuild task that did this. An AOP framework like PostSharp might help you accomplish this at comiple-time by piggy backing on it's build task model.
But what is wrong with code analysis or run-time enforcement? Maybe it's just preference and I respect that, but I personally have no issues with having CA/FXCop check these things... and if you really want to force downstream implementers of your classes to have constructor signatures, you can always add rules run-time checking in the base class constructor using reflection.
Richard
I'm unsure as to what you are trying to achieve, can you please elaborate? The only reason for forcing a specific constructor or static method accross different classes is to try and execute them dynamically at run time, is this correct?
A constructor is intended to be specific to a particular class, as it is intended to initialise the specific needs of the class. As I understand it, the reason you would want to enforce something in a class hierarchy or interface, is that it is an activity/operation relevant to the process being performed, but may vary in different circumstances. I believe this is the intended benefit of polymorphism, which you can't achieve using static methods.
It would also require knowing the specific type of the class you wanted to call the static method for, which would break all of the polymorphic hiding of differences in behaviour that the interface or abstract class is trying to achieve.
If the behaviour being represented by the constructor is intended to be part of the contract between the client of these classes then I would add it explicitly to the interface.
If a hierarchy of classes have similar initialisation requirements then I would use an abstract base class, however it should be up to the inheriting classes how they find the parameter for that constructor, which may include exposing a similar or identical constructor.
If this is intended to allow you to create different instances at runtime, then I would recommend using a static method on an abstract base class which knows the different needs of all of the concrete classes (you could use dependency injection for this).
I have a base class Character which has several classes deriving from it. The base class has various fields and methods.
All of my derived classes use the same base class constructor, but if I don't redefine the constructor in my derived classes I get the error:
Error: Class "child class" doesn't contain a constructor which takes this number of arguments
I don't want to redefine the constructor in every derived class because if the constructor changes, I have to change it in every single class which, forgive any misunderstanding, goes against the idea of only writing code once?
You can use the following syntax to call the base class constructor from the classes that derive from it:
public DerivedClass() : base() {
// Do additional work here otherwise you can leave it empty
}
This will call the base constructor first, then it will perform any additional statements, if any, in this derived constructor.
Note that if the base constructor takes arguments you can do this:
public DerivedClass(int parameter1, string parameter2)
: base(parameter1, parameter2) {
// DerivedClass parameter types have to match base class types
// Do additional work here otherwise you can leave it empty
}
You can find more information about constructors in the following page:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/using-constructors
In a derived class, if a base-class constructor is not called explicitly by using the base keyword, the default constructor, if there is one, is called implicitly.
You do have to redeclare constructors, because they're effectively not inherited. It makes sense if you think of constructors as being a bit like static methods in some respects.
In particular, you wouldn't want all constructors to be automatically inherited - after all, that would mean that every class would have a parameterless constructor, as object itself does.
If you just want to call the base class constructor though, you don't need to write any code in the body of the constructor - just pass the arguments up to the base class as per Waleed's post.
If your base class starts requiring more information, it's natural that you should have to change all derived classes - and indeed anything calling the constructors of those classes - because they have to provide the information. I know it can seem like a pain, but it's just a natural consequence of what constructors do.
I had the same problem, and I solved it by replacing my constructor with a factory method like this:
A is the parent class.
public static T getChild<T>(int number) where T:A, new()
{
T child = new T();
T._number = number;
return child;
}
You can create a Child class with
Child b = A.getChild<Child>(2);
A kind of alternative could be to rely on a Dependency Injection container to initialize your objects, that way the that reference to the base class (could be the call to the base constructor or another initializer method) would "externalized" to the DI container.
I don't know if it makes sense to your case or not
Lets take an example in C#
public class Foo
{
public Foo() { }
public Foo(int j) { }
}
public class Bar : Foo
{
}
Now, All the public members of Foo is accessible in Bar except the constructor.
I cannot do something like
Bar bb = new Bar(1);
Why the constructors are not inheritable?
UPDATE
I do understand we can chain constructors, but I would like to know why the above construct is not valid. I am sure there should be a valid reason for it.
Constructors are not inheritable because it might cause weird and unintended behavior. More specifically, if you added a new constructor to a base class, all derived classes get an instance of that constructor. That's a bad thing in some cases, because maybe your base class specifies parameters that don't make sense for your derived classes.
A commonly given example for this is that in many languages, the base class for all objects (commonly called "Object") has a constructor with no parameters. If constructors were inherited, this would mean that all objects have a parameterless constructor, and there's no way to say "I want people who make an instance of this class to provide parameters X, Y and Z, otherwise their code shouldn't compile." For many classes, it's important that certain parameters be defined for their proper function, and making constructors non-heritable is part of the way that class authors can guarantee that some parameters are always defined.
Edit to respond to comments: Ramesh points out that if constructors were inherited as he would like them to be, he could always override base class constructors using privately declared constructors in each derived class. That is certainly true, but there it a logistical problem with this strategy. It requires that writers of derived classes have to watch base classes closely and add a private constructor if they want block inheritance of the base class constructor. Not only is this a lot of work for people writing derived classes, this kind of implicit dependency across classes is exactly the sort of thing that can cause weird behavior.
Ramesh - it's not that what you describe would be impossible to add to a language. In general it's not done because that sort of behavior could confuse people and lead to a lot of extra debugging and code writing.
Quintin Robinson provides some very worthwhile responses to this question in the comments that are definitely worth reading.
They are (via chaining), you would have to chain the constructor in your derived object.. IE:
public class Foo
{
public Foo() { }
public Foo(int j) { }
}
public class Bar : Foo
{
public Bar() : base() { }
public Bar(int j) : base(j) { }
}
The constructors in the derived objects will then chain the calls do the constructors in the base objects.
This article provides some more examples if you want further reading.
One reason why you might introduce a constructor into a class is because it makes no sense to have an instance of that class without a specific "dependency". For example, it might be a data-access class that has to have a connection to a database:
public class FooRepository
{
public FooRepository(IDbConnection connection) { ... }
}
If all the public constructors from base classes were available, then a user of your repository class would be able to use System.Object's default constructor to create an invalid instance of your class:
var badRepository = new FooRepository();
Hiding inherited constructors by default means that you can enforce dependencies without worrying about users creating "invalid" instances.
Suppose constructors were inheritable. How would you disable the inherited constructors in the many cases were they don't make sense for a subclass?
Rather than complicating the language with a mechanism to block inheritance, the language designers opted for simply making constructors not inheritable.
The Foo constructor can only know how to initialize a Foo object, so it makes no sense that it should also know how to initialize any potential subclass
public class Bar : Foo
{
public Bar(int i) : base(i) { }
}
The story the constructor tells is: "Hey base class please do whatever work you need to do to be in a good state so that I can go ahead and set up myself properly".
Constructors are not inheritable for design reasons. (Note that this is the same situation in every object-oriented language of which I know.) The simple answer is that in many cases you'd really not want the same constructors as the base class to be available. See this SO thread for some more complete explanations.
Some discussions
Joel's forum
Eric Gunnerson's blog
The basic idea is to provide as much control to the creator as possible. And you can have private bases. How'd you create the object then?
I think you can do the following:
public class Bar : Foo
{
public Bar (int i)
: base (i)
{
}
}
I may be a bit off -- but it's the general idea.
The simple answer is that the language doesn't work that way.
The real question you are asking for though is why it doesn't work that way :-) Well it is an arbitrary choice, and it follows on from C++ and Java (and very possibly many other langauges that influenced C#).
The likely reason is that the compiler will only generate a constructor that takes no arguments and simply calls the parent is that if you want more than what the compiler makes you do it yourself. This is the best choice since odds are you do more than suply calling the parent constructor.
Really, its because the parent constructor wouldn't fully initialize the child object. A constructor is kind of a personal thing in that respect. That's why most languages don't inherit constructors.