1

Possible Duplicate:
Interface defining a constructor signature?

I can declare methods and properties in an Interface and impose the class that implements it to implement these methods and properties. Similarly is it possible to impose a rule such that all my classes which implement a certain interface should always have a parametrized constructor?

Am not sure if this is possible. Just a thought.

Thanks

Community
  • 1
  • 1
Nishant
  • 905
  • 1
  • 16
  • 36

3 Answers3

4

Similarly is it possible to impose a rule such that all my classes which implement a certain interface should always have a parametrized constructor?

No, not through interface declarations.

You can create an abstract class instead and it can have a parametrized constructor - all implementing types will inherit the constructor and will be able to chain to it using the base keyword. Note that this will not stop you inheriting types from implementing parameterless constructors.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
1

No, but if your goal is to normalize how instances of an interface are constructed, define another interface that is a factory for instances of the first. In the factory interface you can impose the required construction parameters.

interface IFoo
{
    ...
}

interface IFooFactory
{
    IFoo CreateFoo(string param1, string param2)
}
  • Thanks..this looks like what I want. Can you please elaborate a bit more on this? How would class Foo look like? – Nishant Jul 14 '12 at 19:41
0

A class have contructor and interface cannot. So you cannot in force classes that implement certain interface to have a parameterised contructor

But you can have a class with a multiple constructors and its children can have a choice which constructor they want to use

HatSoft
  • 11,077
  • 3
  • 28
  • 43