Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

static interface methods

Status
Not open for further replies.

jby1

Programmer
Apr 29, 2003
403
GB
Hi

I would like to specify an interface, but have the classes that implement it do so with static methods. eg:

Code:
public interface IFace1
{
    bool MethodOne();
}

public class Class1 : IFace1
{
    public static bool MethodOne();
}

It seems that I am not allowed to do this. Does anybody have any suggestions how I could achieve what I want here?

Thank you!

PS I am still new to C#!!
 
An interface is a contract with the compiler that your objects (not your Types!) will be able to handle a function call through that interface. A static method is called with a Type, not an object, and you cannot get an interface handle on a Type. Basically, what you claim you want is not syntactically or semantically correct (there might be a better way of approaching the problem that is).

But it can still be done, in a way. You can use Reflection to verify that a Type has a static function of a certain name and call that function.

Once again, I think that you probably want something different than what you are asking for.

"Programming is like sex, one mistake and you have to support it forever."

John

johnmc@mvmills.com
 
This is what I want to do. I have a set of classes, each of which access a database table. I would like to use static methods for these classes as I don't want to have to instantiate these every time I want to use them. There is no state associated with them.

There are also families of database classes, which share common access methods. Therefore I would like to represent each family with an interface, so that the code calling does not have to be hardcoded for the tables it wants to access.

I do not want to do that Reflection stuff you have talked about, seems overly complex. I suppose there is no reason why I need to have static methods.

Perhaps I could use a Singleton to minimize the number of database objects to one for each table. Does this sound reasonable?

Or perhaps this is also wrong, and there is a better way?
 
The two options that I can think of for what you have described are:

1. Create one class with several static functions (one for each class of access), then pass variables to that function to determine eactly what to do.

2. Use a static member variable (Singleton like you suggested) to hold your database object.

"Programming is like sex, one mistake and you have to support it forever."

John

johnmc@mvmills.com
 
Cheers! I am going to see how it goes with the Singleton.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top