473,554 Members | 2,152 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Declaring a Constructor in an Interface?

I am accessing my database through an interface, to allow future
substitution of the physical datastore - hence I would like to declare in my
Interface that my DAL-objects implementing the interface and accessing the
datastore MUST pass in a UserToken in the constructor of the object.

Is this not possible?
Am I forced to add the UserToken as a property on the object instead?

/Ole

Nov 16 '05 #1
20 4226
Unfortunately this is not possible.

You may use an abstract class instead which exposes 1 constructor
taking a UserToken though.

I really wished that this was possible, because interfaces are faster than
abstract classes.

--
Regards,
Dennis JD Myrén
Oslo Kodebureau
"Ole Hanson" <ol********@ole .ole> wrote in message
news:eg******** ******@TK2MSFTN GP09.phx.gbl...
I am accessing my database through an interface, to allow future
substitution of the physical datastore - hence I would like to declare in my Interface that my DAL-objects implementing the interface and accessing the
datastore MUST pass in a UserToken in the constructor of the object.

Is this not possible?
Am I forced to add the UserToken as a property on the object instead?

/Ole

Nov 16 '05 #2
What leads you to the conclusion that interfaces are faster than ABCs?

Regards

Richard Blewett - DevelopMentor

http://staff.develop.com/richardb/weblog

nntp://news.microsoft. com/microsoft.publi c.dotnet.langua ges.csharp/<2V************ *******@news4.e .nsc.no>

Unfortunately this is not possible.

You may use an abstract class instead which exposes 1 constructor
taking a UserToken though.

I really wished that this was possible, because interfaces are faster than
abstract classes.

--
Regards,
Dennis JD Myr?n
Oslo Kodebureau
"Ole Hanson" <ol********@ole .ole> wrote in message
news:eg******** ******@TK2MSFTN GP09.phx.gbl...
I am accessing my database through an interface, to allow future
substitution of the physical datastore - hence I would like to declare in my Interface that my DAL-objects implementing the interface and accessing the
datastore MUST pass in a UserToken in the constructor of the object.

Is this not possible?
Am I forced to add the UserToken as a property on the object instead?

/Ole


---
Incoming mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.760 / Virus Database: 509 - Release Date: 10/09/2004

[microsoft.publi c.dotnet.langua ges.csharp]
Nov 16 '05 #3
You need to create 2 class instances
when creating an instance of a class which is derived from an abstract
class.

Creating an instance of an abstract class means performance overhead.
I think that is especially true if the abstract class contains virtual
methods.

Virtual methods always means performance overhead.
According to Microsoft they are two times as expensive as non-virtual
methods.

However, abstract members should be as fast as interface members i believe.

An abstract class containing no virtual methods should be nearly as fast
as an interface, but still slower.

--
Regards,
Dennis JD Myrén
Oslo Kodebureau
"Richard Blewett [DevelopMentor]" <ri******@devel op.com> wrote in message
news:%2******** ********@TK2MSF TNGP10.phx.gbl. ..
What leads you to the conclusion that interfaces are faster than ABCs?

Regards

Richard Blewett - DevelopMentor

http://staff.develop.com/richardb/weblog

nntp://news.microsoft. com/microsoft.publi c.dotnet.langua ges.csharp/<2V************ *******@news4.e .nsc.no>
Unfortunately this is not possible.

You may use an abstract class instead which exposes 1 constructor
taking a UserToken though.

I really wished that this was possible, because interfaces are faster than abstract classes.

--
Regards,
Dennis JD Myr?n
Oslo Kodebureau
"Ole Hanson" <ol********@ole .ole> wrote in message
news:eg******** ******@TK2MSFTN GP09.phx.gbl...
> I am accessing my database through an interface, to allow future
> substitution of the physical datastore - hence I would like to declare in
my
> Interface that my DAL-objects implementing the interface and accessing

the > datastore MUST pass in a UserToken in the constructor of the object.
>
> Is this not possible?
> Am I forced to add the UserToken as a property on the object instead?
>
> /Ole
>
>
>


---
Incoming mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.760 / Virus Database: 509 - Release Date: 10/09/2004

[microsoft.publi c.dotnet.langua ges.csharp]

Nov 16 '05 #4
Dennis,

this isn't how it works. The base class state and the derived class state are combined into a single object and teh v-tables are combined with the oerridden methods replacing the base class versions in the v-table. You are absoilutely right that virtua dispatch is (marginally) slower than non-virtual due to an extra level of indirection (a lookup that has to be performed at runtime - by lookup I don't mean a search by name or anything like that).

Interfaces are essentially a definition of a v-table and time implementations are a bunch of overrides. Interface based invocation uses virtual dispatch - there is no extra overhead from an ABC compared with an interface.

Regards

Richard Blewett - DevelopMentor

http://staff.develop.com/richardb/weblog

nntp://news.microsoft. com/microsoft.publi c.dotnet.langua ges.csharp/<bP************ *******@news4.e .nsc.no>

You need to create 2 class instances
when creating an instance of a class which is derived from an abstract
class.

Creating an instance of an abstract class means performance overhead.
I think that is especially true if the abstract class contains virtual
methods.

Virtual methods always means performance overhead.
According to Microsoft they are two times as expensive as non-virtual
methods.

However, abstract members should be as fast as interface members i believe.

An abstract class containing no virtual methods should be nearly as fast
as an interface, but still slower.

--
Regards,
Dennis JD Myr?n
Oslo Kodebureau
"Richard Blewett [DevelopMentor]" <ri******@devel op.com> wrote in message
news:%2******** ********@TK2MSF TNGP10.phx.gbl. ..
What leads you to the conclusion that interfaces are faster than ABCs?

Regards

Richard Blewett - DevelopMentor

http://staff.develop.com/richardb/weblog

nntp://news.microsoft. com/microsoft.publi c.dotnet.langua ges.csharp/<2V************ *******@news4.e .nsc.no>
Unfortunately this is not possible.

You may use an abstract class instead which exposes 1 constructor
taking a UserToken though.

I really wished that this was possible, because interfaces are faster than abstract classes.


Nov 16 '05 #5
Hi,
Unfortunately this is not possible.
<snip>
I really wished that this was possible, because interfaces are faster than
abstract classes.


I was thinking about it a long time ago...
.... and i came to conclusion that it should not be an interface.
An abstract constructor in an abstract class has no sense, too.

AFAIK interface works only after initialization of its inherited class,
never before. So, there is no way to initialize class by its interface.
This dogma of interface should not be changed.

Regards

Marcin
Nov 16 '05 #6
Dennis Myrén wrote:
You need to create 2 class instances when creating an instance
of a class which is derived from an abstract class.
No you don't. You end up defining two types, but you only create one
instance.

Here's an example:

public abstract class ABC
{
public abstract void SayHello();
}

public class ConcreteDerived : ABC
{
public override void SayHello() { Console.WriteLi ne("Hello!"); }
}

And now to use this:

ABC obj = new ConcreteDerived ();
obj.SayHello();

I have created just one instance here. I have defined two classes, but I've
only created one instance. (In fact it's impossible to create an instance of
the base class, ABC, because it's abstract. So I couldn't create an instance
of each even if I wanted to.)

(Note, by the way, that this doesn't actually solve the problem as
originally stated. Abstract Base Classes aren't a solution to this
particular issue because you can't inherit constructor signatures.)

Creating an instance of an abstract class means performance
overhead.
I think that is especially true if the abstract class contains
virtual methods.
You can't create an instance of an abstract class. That's what 'abstract'
means!

Also, the presence of virtual methods has no impact on the overhead of
creating an instance of a class, so your argument is slightly confused here
I'm afraid.

There are overheads to virtual methods, but you've missed an important point
here:
Virtual methods always means performance overhead.
According to Microsoft they are two times as expensive as
non-virtual methods.
Yes, but interfaces are even more expensive.

So if you chose to use interfaces instead of abstract base classes to avoid
the overhead of a virtual function call, you've made a bad choice.
Interface method calls are even more expensive than virtual function calls.

The expensive thing is the polymorphic nature of the call. With either
interfaces or virtual methods, the method that ends up getting called will
depend on what type of object you've got, so the JIT-compiled code can't
just call the relevant function directly or inline it. You pay that cost
with either virtual methods or interfaces. And as it happens, interface
method calls are marginally the more expensive of these two call types
today.

(In Whidbey, the next version of .NET, it all gets a little more complex to
work out how much a method call costs, because they appear to detect when
you're not actually exploiting polymorphism and change the way the code
works. It's similar to a technique called 'monomorphic inlining' that some
JVMs use. This means that the cost of polymorphic function calls changes
over time.)

However, abstract members should be as fast as interface members i
believe.
Abstract members *are* virtual. If you use ILDASM to look at what the
compiler generates, this becomes very clear. For example, here's the
abstract SayHello method as defined in my ABC class above:

..method public hidebysig newslot abstract virtual
instance void SayHello() cil managed
{
} // end of method ABC::SayHello

Notice that it is marked as 'abstract virtual'. In the IL, this is
explicit. With C#, to save you typing, they don't make you type in both -
abstract methods *have* to be virtual. A non-virtual abstract method makes
no sense: 'abstract' effectively means 'must override', and you can only
override virtual methods. So if you were to define a non-virtual abstract
method you would effectively be defining a method that derived classes were
required to override, but which couldn't be overridden!

So because 'abstract' only makes sense for virtual methods, in C# writing
'abstract' always implies 'virtual'.

So abstract methods are exactly as expensive as virtual methods, for the
simple reason that they *are* virtual methods.

An abstract class containing no virtual methods should be nearly as
fast as an interface, but still slower.


An abstract class containing no virtual methods would be a slightly unusual
thing, because it would contain no abstract methods... It is actually
possible to write such a class, you just wouldn't normall do it. It would
in fact be substantially faster to use than call interface methods, because
non-virtual methods (which includes all non-abstract methods) are faster
than either virtual methods or interface method calls. But it wouldn't be a
very useful thing - you don't often want to declare an abstract class with
no abstract methods.

But how would an abstract class containing some abstract methods stack up
against an interface? In the current version of the CLR, interface calls are
known to be slightly more expensive, so you would expect this:

Fastest: direct call to non-abstract, non-virtual, non-interface methods
2nd fastest: call through abstract or virtual method
Slowest: call through interface method

But it's always important to test, so I wrote a little program that sees how
many calls a second I can get through each type. Here are the results:

Direct call: 515 million calls per second
Abstract method: 173 million calls per second
Interface method: 155 million calls per second

That's on my laptop, with a 1.6GHz Pentium M, running v1.1 of the .NET
framework. I've copied the program at the end of this message so you can
try it out.

This seems to confirm that interfaces are (on the current .NET framework)
the slowest of the three options. And for this particular test, a
non-abstract, non-interface call is well over twice as fast.

In any case, not only is this not really relevant to the original discussion
(abstract base classes don't help solve the problem any better than
interfaces) this is a bit of a case of micro-optimization. The difference in
performance between these different types of method calls is very often
going to be irrelevant - if the method does anything non-trivial, then the
cost of the work it does will swamp any difference between invocation costs.
(These distinctions really only matter for very simple methods like
straightforward property accessors. In that case, the main difference is
that with a non-interface and non-virtual call, the JIT compiler can inline
the method.)
--
Ian Griffiths - http://www.interact-sw.co.uk/iangblog/
DevelopMentor - http://www.develop.com/

using System;

public abstract class ABC
{
public abstract void SayHello();
}

public interface IFoo
{
void SayHello();
}

public class ConcreteDerived : ABC
{
public override void SayHello() { }
}

public class InterfaceImpl : IFoo
{
public void SayHello() { }
}

public class NonVirtual
{
public void SayHello() { }
}
class App
{
static void Main()
{
// Run tests multiple times to avoid any transient
// JIT-related overheads

for (int i = 0; i < 5; ++i)
{
SpeedTestNonVir tual(new NonVirtual());
SpeedTestABC(ne w ConcreteDerived ());
SpeedTestInterf ace(new InterfaceImpl ());
}
}
const int CallsBetweenTim eChecks = 100000;
static void SpeedTestNonVir tual(NonVirtual obj)
{
DateTime stopBy = DateTime.Now + TimeSpan.FromSe conds(10);
long count = 0;
while (DateTime.Now < stopBy)
{
// Make lots of calls in between time checks, otherwise
// the time take to check the current time dominates.

for (int i = 0; i < CallsBetweenTim eChecks; ++i)
{
obj.SayHello();
count += 1;
}
}
Console.WriteLi ne("Non-virtual: {0} million calls per second", ((double)
count) / 10000000.0);
}

static void SpeedTestABC(AB C obj)
{
DateTime stopBy = DateTime.Now + TimeSpan.FromSe conds(10);
long count = 0;
while (DateTime.Now < stopBy)
{
// Make lots of calls in between time checks, otherwise
// the time take to check the current time dominates.

for (int i = 0; i < CallsBetweenTim eChecks; ++i)
{
obj.SayHello();
count += 1;
}
}
Console.WriteLi ne("ABC: {0} million calls per second", ((double) count)
/ 10000000.0);
}

static void SpeedTestInterf ace(IFoo obj)
{
DateTime stopBy = DateTime.Now + TimeSpan.FromSe conds(10);
long count = 0;
while (DateTime.Now < stopBy)
{
// Make lots of calls in between time checks, otherwise
// the time take to check the current time dominates.

for (int i = 0; i < CallsBetweenTim eChecks; ++i)
{
obj.SayHello();
count += 1;
}
}
Console.WriteLi ne("Interface: {0} million calls per second", ((double)
count) / 10000000.0);
}
}
Nov 16 '05 #7
Ole Hanson wrote:
I am accessing my database through an interface, to allow future
substitution of the physical datastore - hence I would like to declare
in my Interface that my DAL-objects implementing the interface and
accessing the datastore MUST pass in a UserToken in the constructor
of the object.

Is this not possible?
Am I forced to add the UserToken as a property on the object instead?


The usual solution to this is to define some kind of factory interface,
e.g.:

public interface IDALFactory
{
IDataStoreObjec t CreateNewObject (UserToken token);
}

or whatever happens to make sense for your particular code.

There are two reasons for doing this:

(1) there is no mechanism in .NET today to impose a constraint that requires
a particular class to provide a particular constructor. Interfaces cannot do
this because interfaces are always purely abstract; since they cannot be
constructed they don't have any notion of constructors. And base classes
can't do this either because for various reasons, derived classes don't
inherit constructors in the same way as normal methods - the only visible
constructors on the derived class are those you write explicitly. The base
class constructors are available to the derived class itself, but they are
not visible as part of its public API. So this:

public class BaseWithCtor
{
public BaseWithCtor(st ring foo) { }
public BaseWithCtor() { }
}

has two constructors. But this:

public class Derived : BaseWithCtor
{
}

only has the one - it has the compiler-generated default no-params
constructor. But if you try this:

Derived d = new Derived("Hello! ");

it doesn't work. Even though the base class has a constructor with this
signature, the derived class doesn't inherit that as part of its public
interface.
(2) the other reason for using a factory interface is that even if the
restrictions in (1) didn't exist, you wouldn't be any better off. Your goal
is to be able to substitute a different implementation in the future. This
means that you can never actually use a constructor in your code directly.
For example, suppose you have this kind of code:

IDataStoreObjec t obj = new TodaysImplement ation(UserToken tok);

then even if some mechanism had been available to enforce the requirement
that TodaysImplement ation had that constructor, how does this help you with
TomorrowsImplem entation? Even though TomorrowsImplem entation might also be
forced to have the right constructor, you're still left with the rather more
fundamental problem that the code above has a hard-coded dependency on the
TodaysImplement ation type.

So if you need to be able to substitute in different implementations , you
can't just use the new operator. You're going to have to go via some kind of
factory abstraction to enable the right type to be selected in any case. So
all that matters then is that the factory API takes the parameters you need.
You don't actually need to care how a particular DAL implements the factory.
In particular you won't need to care what constructors are used, so long as
the objects returned by the factory are correctly initialized. Whether this
was done with a particular type of constructor, or with properties or some
other mechanism is an implementation detail of the DAL.
--
Ian Griffiths - http://www.interact-sw.co.uk/iangblog/
DevelopMentor - http://www.develop.com/
Nov 16 '05 #8
Well, in that case I have to apologize if i was wrong.
However, i have read many places that an interface is faster than
an abstract class. This is one of them:
http://www.dotnetspider.com/Technolo...x?SampleId=492

I wont argue with You, but would You also claim that an abstract class
containing only abstract members
is faster than an interface as well? In that case, what is the benefit of
interfaces anyway?

I have always believed interfaces were superior to abstract classes.
I apologie for the misleading information i might have given.

--
Regards,
Dennis JD Myrén
Oslo Kodebureau
"Dennis Myrén" <de****@oslokb. no> wrote in message
news:bP******** ***********@new s4.e.nsc.no...
You need to create 2 class instances
when creating an instance of a class which is derived from an abstract
class.

Creating an instance of an abstract class means performance overhead.
I think that is especially true if the abstract class contains virtual
methods.

Virtual methods always means performance overhead.
According to Microsoft they are two times as expensive as non-virtual
methods.

However, abstract members should be as fast as interface members i believe.
An abstract class containing no virtual methods should be nearly as fast
as an interface, but still slower.

--
Regards,
Dennis JD Myrén
Oslo Kodebureau
"Richard Blewett [DevelopMentor]" <ri******@devel op.com> wrote in message
news:%2******** ********@TK2MSF TNGP10.phx.gbl. ..
What leads you to the conclusion that interfaces are faster than ABCs?

Regards

Richard Blewett - DevelopMentor

http://staff.develop.com/richardb/weblog

nntp://news.microsoft. com/microsoft.publi c.dotnet.langua ges.csharp/<2V************ *******@news4.e .nsc.no>

Unfortunately this is not possible.

You may use an abstract class instead which exposes 1 constructor
taking a UserToken though.

I really wished that this was possible, because interfaces are faster

than
abstract classes.

--
Regards,
Dennis JD Myr?n
Oslo Kodebureau
"Ole Hanson" <ol********@ole .ole> wrote in message
news:eg******** ******@TK2MSFTN GP09.phx.gbl...
> I am accessing my database through an interface, to allow future
> substitution of the physical datastore - hence I would like to
declare in
my
> Interface that my DAL-objects implementing the interface and
accessing the > datastore MUST pass in a UserToken in the constructor of the object.
>
> Is this not possible?
> Am I forced to add the UserToken as a property on the object instead?
>
> /Ole
>
>
>


---
Incoming mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.760 / Virus Database: 509 - Release Date: 10/09/2004

[microsoft.publi c.dotnet.langua ges.csharp]


Nov 16 '05 #9
Dennis Myrén <de****@oslokb. no> wrote:
Well, in that case I have to apologize if i was wrong.
However, i have read many places that an interface is faster than
an abstract class. This is one of them:
http://www.dotnetspider.com/Technolo...x?SampleId=492


Well, that talks about JVMs rather than CLRs, so is somewhat dubious to
start with. However, it does say that JVMs are reducing the performance
penalty anyway.

Do you have any evidence that for any app that you've written, the
method call itself has been the bottleneck? I suspect it's a very rare
case where this is actually an issue, even if interface method calls
*are* twice as fast as abstract class method calls (which I'm not
convinced of yet).

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
2391
by: Carlos Ribeiro | last post by:
Hello all, I'm posting this to the list with the intention to form a group of people interested in this type of solution. I'm not going to spam the list with it, unless for occasional and relevant announcements. If you're interested, drop me a note. But if for some reason you think that this discussion is fine here at the c.l.py, please let...
21
10125
by: Steve - DND | last post by:
I know it's possible to require inheriting classes to implement a particular function or property, but is it possible to require a inheriting class to implement a constructor of it's own? Thanks, Steve
10
2231
by: linkspeed | last post by:
Following texts are from C# spec. The optional constructor-initializer specifies another instance constructor to invoke before executing the statements given in the constructor-body of this instance constructor. This is described further in Section 10.10.1. So this means:
4
17175
by: Peter | last post by:
I want to copy a parent class instance's all datas to a child's. It's actually a C++'s copy constructor. But why the following code does not work - there is a compile error! How it should look like? (The background is I don't know (I don't care indeed) all members in DataGrid, so I don't want to copy all members in DataGrid one by one.) ...
14
2702
by: Arne | last post by:
In C++ we have a copy constructor. What is the equivalent in .Net? Would that be a clone method?
15
2943
by: CR | last post by:
I've noticed that the trend these days is to declare variables in the middle of code instead of at the top. What is the advantage of this? It seems like it makes it hard to reuse variables. Here is how all the examples I've seen so far create an OleDbCommand Object: Dim cmd as new OleDbCommand("Select * FROM Table1",cnn) I had to...
1
6794
by: Ruffin Bailey | last post by:
I want to declare an interface that forces the presence of a certain constructor (in this case, "Sub New(ByVal ds As DataSet)"). When I try, I get a 'Sub New' cannot be declared in an interface. .... error. Now I could create an object that implements the interface that includes the contructor and extend it, sure, but as I understand...
10
6554
by: AZRebelCowgirl73 | last post by:
This is what I have so far: My program! import java.util.*; import java.lang.*; import java.io.*; import ch06.lists.*; public class UIandDB {
2
3884
by: gilbert | last post by:
Hello. I am trying to use c# generic to define a class. class MyClass<Twhere T: new(){ } In this definition, MyClass can create T objects with a default constructor. Is there any way to set the constraint such that MyClass
0
7605
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7530
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8047
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
6156
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5441
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5162
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3570
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3556
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
845
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.