TrevorW

I think most know we cannot declare a static anything in an interface. However, let's say I have this:

public sealed class MyClass {

private MyClass(string someText) {
m_someModifiedText = someText;
}

private readonly static m_someModifiedText;

public static MyClass Create( string someText ) {
string modifiedText= ModifyText(someText);
return new MyClass(someText);
}

private string ModifyText(string someText) {
string modifiedText = someText;
//do something to modify text
return modifiedText;
}

public static string UsefulText {
return m_someModifiedText;
}

}

Now, this "sample" is just to keep it simple, but PLEASE just consider the concept rather than what the class is trying to do.

To create an instance, I MUST use the static method of MyClass.Create(someText). For example,

string someText = "foo";
MyClass mc = MyClass.Create(someText);

This is very different than using a constructor and I think many understand "why" this is done.

The problem is that interfaces cannot require static members of any kind, yet I do "desire" an interface to have knowledge about the Create(someText) method... or ... at least a workaround.

This "seems" so simple, just allow static method declarations in interfaces.

public interface IMyInterface {
static IMyInterface Create(string someText);
}

... or , at least, alow static method declarations if the type returned is the same as the interface it is declared in.

I have looked for "good reasons" why this is not allowed and have come up empty. The MyClass example from above would not have any possible interface members and this seems just wrong.

Is there no workaround or any answer for these type of scenarios

Thanks,

Trevor



Re: Visual C# Language static method - Is there any workaround?

Sean Hederman

No there is no workaround for this. The simplest reason why is that an interface cannot have implementation by definition. If it has implementation, then it's not an interface. So what you're really looking for is an abstract base class.






Re: Visual C# Language static method - Is there any workaround?

TrevorW

I don't want it implemented, I just want it to be required and I am sure that I am not alone here.

The whole point of an interface is that signatures are NOT implemented and that is what I want. In fact, the correct answer is the reverse or opposite of what you state: an interface requires that each member be potentially unique for every instance. A static member cannot be unique for any instance, but this rule "stinks" and I think is miguided.

We have instancing driving the rules versus the "true" nature of an interface which is a contract. A contract should be capable of stating that members cannot be modified at the instance level, but there is no way to define that within an interface. The 'typical' answer provided is always based on 'instance' "bs" (IMO).

I'm sorry, but a contract should not be so restricted such that every instance is freely modified. A contract needs to limit modification to the implementation.

Now, you are correct that abstract classes can have static members defined, but then we ar forced to a hierarchy that may not make sense. We are forced because an abstract class can only be inherited once as oppsed to interfaces which can be inherited multiple times. What happens when I need the equivalent of two separate abstract classes implemented simultaneously I cannot! However, I can build up bogus hierarchies such that one i the parent of another, but if that is not the true nature of the relationship, I will be stuck when one appears as a child and it should be an equal.

Again, I simply cannot undrstand why the compiler team cannot support static members in an interface.

Trvor





Re: Visual C# Language static method - Is there any workaround?

Sean Hederman

Okay, let's put it this way. We have an interface that requires a static method. Who exactly is going to implement that method Every class that implements the interface Of course not, because then it wouldn't be static would it Would it perhaps require that one implemented it If so, are we talking one implementation per assembly What happens if we reference an assembly that already has it implemented Would we have to provide a mechanism to override the static If so, since there is no hierarchy, and all implementations are on the same level as it were, how would we do that

Why on earth would we even attempt to resolve these issues and questions (if they are even solvable) if there is no need for this Frankly, your example is screaming for the abstract factory pattern, not for a whosesale reevaluation of how interfaces work.






Re: Visual C# Language static method - Is there any workaround?

TrevorW

>>Okay, let's put it this way. We have an interface that requires a static method. Who exactly is going to implement that method Every class that implements the interface

Ummm _YES! - Thats the entire point, the question is - who wouldn't - it should not be possible to not implement a member of an interface. Wh is not getting this (me or you). The same class gets "instantiated" multiple times and then the method would HAVE to remain the same between instances. Different "classes" are NOT the same scope here as different instances of the same class. Sorry, you are wrong! (IMO)

>>What happens if we reference an assembly that already has it implemented

Umm - are you serious

Maybe I really am misunderstanding, but an interface is not implemented UNTIL the class that implements it actually does. Let's say I have:

public interface IMyInterface {
static IMyInterface Create(string foo);
}

Nothing in the assembly is instantiated anywhere - its an interface!

Now I implement the interface:

public class MyClass: IMyInterface {
public static IMyInterface Create(string foo) {
IMyInterface blahBlah = new MyClass();
return blahBlah;
}
}

Please, tell me whay another class cannot implement the same interface within the same assembly and not have a different implementation

For example,

public class MyClass2: IMyInterface {
public static IMyInterface Create(string foo) {
IMyInterface blahBlah = new MyClass2();
return blahBlah;
}
}

Notice the 2 in MyClass2

Notice that the we CAN have TWO or MORE implementations

Notice that they CAN be in the same assembly

Now, what cannot happen is a change in derived class from the ones created above unless the method ('Create') is overriden, but isn't that the desired effect We want ALL instances of the same class to have a static member Create as part of the contract. Why is this so hard to get

More importantly I would be able to program to the interface and NOT to an implementation because I would have access to ALL the members including the static method. *Very desirable!

I'm sorry, but I don't get your points because they seem just plain wrong to me.

An abstract class is completely iincapable of separating structure at the same level (I.e. we cannot implement two or more abstract classes) and I already pointed out that your arguments were invalid. It seems you are mistaking/ confusing different instances of the same class which is distinguishably different than instances of separate classes with different implementations.

Trevor





Re: Visual C# Language static method - Is there any workaround?

TrevorW

I will give you one possible "conflict":

public interface IFoo {
static bool IsValid {get;}
}

public interface IBar {
bool IsValid {get;}
}

public class MyClass: IFoo, IBar {
public bool IsValid {
get {return true;}
}
}

Hmmm.. what would happen here One is static and one is not and the names conflict! What to do

Well, all that would have to happen is the interfaces must be fully qualified - explicitly, or a compiler error "should" happen.

public class MyClass: IFoo, IBar {
public static bool IFoo.IsValid {
get {return false;}
public bool IBar.IsValid {
get {return true;}
}
}

.. and THAT should fix the problem!

Trevor





Re: Visual C# Language static method - Is there any workaround?

Sean Hederman

Static methods belong to the type not the instance, so IFoo can have only one implementation of IsValid. That's what you're not getting. As such, a static method can be used independently of any instance, so I can say IFoo.IsValid. Now tell me, if I say that which method does it call exactly The one in MyClass The one in MyClass2 What you're arguing for is a single declaration and multiple definitions, so how do we decide which definition applies to the declaration IFoo.IsValid

I think what you're not getting is this whole instance-independence of static methods. Now let's imagine another scenario. I define IFoo.IsValid, no class implement it, but I call it. Now what There's no MyClass or MyClass2, there is an IFoo, and by the rules of static methods, I am perfectly correct to now say IFoo.IsValid.

In other words you'd have to put the implementation of the IFoo static methods in IFoo itself, any other solution simply would not work. But putting them there wouldn't give you what you're looking for.

Please, read what I'm saying carefully this time, because you quite obviously have not understood my previous objections at all.






Re: Visual C# Language static method - Is there any workaround?

TrevorW

>>Static methods belong to the type not the instance, so IFoo can have only one implementation of IsValid. That's what you're not getting. As such, a static method can be used independently of any instance, so I can say IFoo.IsValid. Now tell me, if I say that which method does it call exactly The one in MyClass The one in MyClass2

Hello - What You keep contradicting yourself! Why do you keep saying it belongs to the "type" on one hand and then demand that each instance must be able to call an instance.

Wake up!

MyClass is a TYPE not an instance! MyClass2 is ANOTHER TYPE, not an instance! As you stated: static methods belong to a TYPE; thus, MyClass and MyClass2 can and SHOULD be able to declare separate and distinct implementations of IFoo.IsValid.

Second you come up with what is rediculous, if you call IFoo.IsValid and "claim" that you never implement it, then - now what

Well, NOTHING! If you never implement it, then due to type safety, you cannot pass anything into the method in which you referred - so it will never be referenced to am actual implementation and nothing will happen. Are you suggesting that interfaces with static members should be treated as constants Who is the moron that is suggesting that

So, again you run with a false premise: that a static declaration in an interface requires the same treatment across all types: that is simply wrong, incorrect - not ACCURATE!

Now, I am referring to what the compiler "should" do, not what is. I get that its not supported now, my argument is that it should be. How hard is it to understand that people are making false statements and I am trying to expose where its false so we can get a real solution and not be stifled - so we can move forward!

Please, do not tell me that a static declaration does not require implementation, by its very nature it does - at the TYPE level (I.e. a class). I already posted where conflict "could" pccur and that is easily recognized and dealt with a compile time and easiy solved by requiring fully qualified implementations when a conflict is recognized - in fact I would be okay with requiring all ataic interface declarations to require a fully qualified namespace reference.

Is there anyone else that understands my point or that can make a solid argument against what I propose I have no problem with being wrong, but what has been presented so far, I do not agree with. I am curious as to the opinions of others - maybe I am missing something and need a slap in the face.

Trevor





Re: Visual C# Language static method - Is there any workaround?

JDPeckham

So what you want is this:

interface : IStaticInterface

{

static IStaticInterface Create(string text);

}

forcing every type to implement Create(string text)

I think that's a very valid thing to do... but obviously you can't do it... so how bout you try something like

interface : IFactoryOnlyObject

{

}

interface : IFactory

{

IFactoryOnlyObject Create(string text)

}

then create a factory that implements IFactory for every object that implements IFactoryOnlyObject....






Re: Visual C# Language static method - Is there any workaround?

nobugz

Let's try it like this:

using System;
public interface IMyInterface {
/*static*/ IMyInterface Create();
}

public class MyClass1 : IMyInterface {
public /*static*/ IMyInterface Create() {
return new MyClass1();
}
}

public class MyClass2 : IMyInterface {
public /*static*/ IMyInterface Create() {
return new MyClass2();
}
}

static class Test {
static void Run() {
MyClass1 obj1 = new MyClass1();
IMyInterface itf1 = CreateInstance(obj1);
}
public static IMyInterface CreateInstance(IMyInterface itf) {
return itf.Create();
}
}

Now remove the comments and assume the language supports static interface members. The compiler needs to generate the code for itf.Create(). Technically, it could make a list of all the visible classes that implement the IMyInterface interface and thus are guaranteed to have a static Create() method. It would find MyClass1 and MyClass2 both containing a static method when the proper signature and implementing the interface. They do however create entirely different classes. The problem: which one is better If you'd say: "well, that's obvious, it should be MyClass1 because that's the instance I passed to CreateInstance", I'd have to say: "yes, that's obvious. But that can only work if Create() is virtual". And virtual is the opposite of static.

The fact that you don't have to explicitly declare a interface's method implementation with the "virtual" keyword might be considered an oversight, C# is otherwise quite adamant about being specific...

I'm struggling to come up with a solution for your specific problem. Maybe I'm too steeped into the "that's the way it works" paradigm. I just don't get why you would need an interface; you did make rather a point of avoiding telling us why. Perhaps you are trying to replace an inheritance solution with an interface That's just not going to work, they serve very different purposes...





Re: Visual C# Language static method - Is there any workaround?

TrevorW

I like this idea and I am going to try it - thanks much!



Re: Visual C# Language static method - Is there any workaround?

TrevorW

>>Now remove the comments and assume the language supports static interface members. The compiler needs to generate the code for itf.Create(). Technically, it could make a list of all the visible classes that implement the IMyInterface interface and thus are guaranteed to have a static Create() method. It would find MyClass1 and MyClass2 both containing a static method when the proper signature and implementing the interface. They do however create entirely different classes. The problem: which one is better If you'd say: "well, that's obvious, it should be MyClass1 because that's the instance I passed to CreateInstance", I'd have to say: "yes, that's obvious. But that can only work if Create() is virtual". And virtual is the opposite of static.

I am not agreeing that there any reasons for a method to be virtual just because I declare it as static in an interface. What am I missing I believe that methods declared as static should require explicit implementation as in a "fully qualified" namespace. Then MyClass would (from the compilers' perspective) be implementing MyClass.Create(), not just Create(). In other words, to support this, I recognize that static methods would have to be tied to the class which implements the interface members and the namespace would have to follow it around like glue for it to work. That doesn't seem too difficult to manage and the benefit would be great. The control over contracts (interfaces) would be much broader and much easier to deal with. Instead I am having to break a single contract into sections - instance and static just because someone on the compiler team doesn't want to track the namespace implemented in a static method.

>>I'm struggling to come up with a solution for your specific problem. Maybe I'm too steeped into the "that's the way it works" paradigm. I just don't get why you would need an interface; you did make rather a point of avoiding telling us why. Perhaps you are trying to replace an inheritance solution with an interface That's just not going to work, they serve very different purposes...

Okay, let's say I have an interface:

public interface ISaltedHash {
string Salt { get;}
string Hash { get;}
bool VerifyPlainPassword(string password);
}

I do not want the implementation to be able to create an instance directly and want the constructor to be private; however I do want "static" Create methods visible as part of the interface:

static ISaltedHash Create(string password);
static ISaltedHash Create(string password, string salt);

Now, I can create an interface as shown above (without static methods) and then create an abstract class and I get that, but I, personally, would like to declare contracts solely with interfaces and the static methods as part of the same logical contract. My idea doesn;t have doesn't particularly make much sense as public services, but it makes alot of sense across App Domains (within a DMZ) and most significantly as a general tool to verify that all members are properly implemented at design time (as in the compiler will crash if they aren't implemented).

Look at it froma simple perspective: I can implement the behavior now, I just can't declare what I am doing via an interface. I can add static members to an implementation, but I cannot declare in an interface that they MUST be implemented. So any logic that it doesn't work is rediculous because it works now. The only difference is the compiler verification. The logic designed behind the compiler "checks" assume that static iterface members are not possible; therefore, we won't let you declare static members. But it is possible if the compiler would keep the fully qualifed namespace associated to an implementation as part of the meta data and the logic enforced static behavior for each implementation. Is is certainly very possible and I would love it. Besides if we don't ask - we never get!

Also, thank you for your well thought out comments.

Trevor





Re: Visual C# Language static method - Is there any workaround?

Sean Hederman

Please show us how you would call these static interface methods.






Re: Visual C# Language static method - Is there any workaround?

theblueeyz

An equally concerning question - how would the CLR know the difference This is why interfaces don't define implementation.. sigh..





Re: Visual C# Language static method - Is there any workaround?

TrevorW

Wow - I am struggling here:

Okay: what is an interface and why do we us it

An interface defines a "contract". What is a contract A contract is a collection of Type members such as simple predefined types (bool, string, integer, etc), Methods (Create, DoSomething(), HandleSomething(), etc.), etc.

We define contracts so that we will have verifications AT COMPILE TIME that defined contract members are implemented. An interface NEVER gaurantees that ANY implementation is correct (does IsValid properly validate and return 'true' when valid - the interface does not know that - hence, unit tests). All we know when we implement an interface is that ALL contract members are included and that the "Type" retuened is the correct "Type".

This class has a static member and this works just fine in C#:

public class SomeClass {
public static bool Foo{};
}

What I cannot do now is define any static members in an interface and here is the "chain" that is used as a reason:

public interface IMyInterface {
static bool IsValid {get;}
}

public class MyClass1: IMyInterface {
static bool IsValid {
get { return true; }
}
}

public class MyClass2: IMyInterface {
static bool IsValid {
get { return false; }
}
}

static class Test {
static void Run() {
MyClass1 obj1 = new MyClass1();
IMyInterface myInterface = CreateInstance(obj1);
}
public static IMyInterface CreateInstance(IMyInterface myInterface) {
return myInterface.IsValid();
}
}

The question posed: What should be returned

Well, its easy! Is it not

MyClass1 was instantiated and MyClass1 returns 'true". We then cast obj1 to IMyInterface as 'myInterface' and then we have the equivalent of a class within a class when we try to create a duplicate static instance (which would be retarded by the way and is simply used as a to answer the question: what happens in this scenario )

So, what "should happen "

Well, we should have a reference in memory to the instance of MyClass1.IsValid which is what is returned within the "duplicate" member (CreateInstance). So, obviously it "should" return 'true'.

Of course this would be rediculous and I see only the worst o programmers ever wanting to do such a thing. Let us consider this: it is possible now if we dont use the iterface, but the actual instance as the defined Type (I.e. MyClass1 versus IMyInterface). However, and VERY IMPORTANTLY - do not use the incorrect defintion of static as mentioned previously: that MyClass1 must have the same static reference as MyClass2: they are separate Types and static members are associated to a Type. For some odd reason I keep getting told that static members should be the same between different types and this is simply false!

So, again static members are defined in actual Types just fine, and they cast just fine when we don;t use an interface.

An interface should define a "contract" and simply enforce that ALL members of the contract are, in fact, implemented.

The other benefit with an interface is that referencing the interface allows for access to interface members and only interface members are passed around. Think of a Winform: the actual instance has many members, but implementing an interface allows passing instances of that interface and ONLY those interface members which is great for performance and memory allocation. So, interfaces also allow for gaurantees of contracts AND allows for ONLY the contract to be passed around.

Lastly, we get the compiler checking that proper implemntations are enforced and we get compiler errors if we forget to include a particular member, a member changes, or the members returns an incorrect type. This is where the problem exists! The compiler is too limited with interfaces and does not allow us to require static implementations in an interface and I want to know WHY

I am still waiting for a reply that is not easily resolved. The benefits are normous, so where is a reason that cannot be resolved