For WinRT, IDL now supports constructs such as this:
[marshaling_behavior(agile)]
[threading(both)]
[activatable(0x06020000)]
[version(0x06020000)]
[static(Windows.Networking.Sockets.IDatagramSocketStatics, 0x06020000)]
runtimeclass DatagramSocket
{
[default] interface Windows.Networking.Sockets.IDatagramSocket;
interface Windows.Foundation.IClosable;
}
I'm curious about the static attribute. What does it mean? How does it relate to the interfaces listed inside the body of the runtimeclass?
Static methods on a winrt interface are implemented as interfaces off the class factory for that class.
For this case, you should call (much winrt overhead elided):
ComPtr<IDatagramSocketStatics> factory;
HRESULT hr = RoGetActivationFactory(<HSTRING for Windows.Networking.Sockets.DatagramSocket>, __iidof(IDatagramSocketStatics), &factory.GetAddressOf());
hr = factory->DatagramFactoryMethod(<Parameters>);
As I mentioned, this is pseudo-code, but it should be sufficient to see how to call the static methods.
COM does not support the notion of static methods of a class, all methods must be instance methods since interface methods are abstract. The attribute allows the language projection to emulate static behavior of a method. Specifically the DatagramSocket.GetEndpointPairsAsync() overloads.
Notable as well is that COM also doesn't support overloads, also solved with an attribute. The methods of IDatagramSockeStatics have the [overload] attribute, the real name of the 2nd overload is GetEndpointPairsWithSortOptionsAsync().
Related
I was converting text to ASCII number in Powershell and having trouble with ToByte(). When I looked at the methods for string, I see that some of them show up with an interface prefix, whilst most don't.
Can anyone tell me the difference between these defintions? Why ToByte() starts with IConvertible, but PadLeft() doesn't? Any why ToString() has both of these notations?
Because those methods with the interface name are Explicit Interface Implementations.
If a class implements two interfaces that contain a member with the
same signature, then implementing that member on the class will cause
both interfaces to use that member as their implementation.
If the two interface members do not perform the same function,
however, this can lead to an incorrect implementation of one or both
of the interfaces. It is possible to implement an interface member
explicitly—creating a class member that is only called through the
interface, and is specific to that interface. This is accomplished by
naming the class member with the name of the interface and a period.
Explicit implementation is also used to resolve cases where two
interfaces each declare different members of the same name such as a
property and a method.
You can also see this listed in the String class documentation under Explicit Interface Implementations.
In an abstract class, I wish to define static methods, but I'm having problems.
In this simple example
abstract class Main {
static String get name;
bool use( Element el );
}
class Sub extends Main {
static String get name => 'testme';
bool use( Element el ) => (el is Element);
}
I receive the error:
function body expected for method 'get:name' static String get name;
Is there a typo in the declaration, or are static methods incompatible with abstract classes?
Dart doesn't inherit static methods to derived classes. So it makes no sense to create abstract static methods (without implementation).
If you want a static method in class Main you have to fully define it there and always call it like Main.name
== EDIT ==
I'm sure I read or heard some arguments from Gilad Bracha about it but can't find it now.
This behaviour is IMHO common mostly in statically typed languages (I don't know many dynamic languages). A static method is like a top level function where the class name just acts as a namespace. A static method has nothing to do with an instantiated object so inheritance is not applicable. In languages where static methods are 'inherited' this is just syntactic sugar. Dart likes to be more explicit here and to avoid confusion between instance methods and static methods (which actually are not methods but just functions because they don't act on an instance). This is not my primary domain, but hopefully may make some sense anyways ;-)
Looks like you are trying to 'override' a static method. I'm not sure what you are trying to achieve there. I'm not aware of any OO languages that support that (and not sure how they could).
A similar question in Java might help clarify Polymorphism and Static Methods
Note also that it is considered bad practice to refer to statics from an instance of the class in Java (and other OO languages). Interestingly I noticed Dart does not let you do this so is in effect removing this bad practice entirely.
So you couldn't even fool yourself into thinking it would behave polymorphically in Dart because you can't call the static from the instance.
I would like to pass an interface to a method signature which takes Object as its parameter, so I wonder about this question
public Stream GetViewStream(string viewName, object model, ControllerContext context)
instead of object I shall like to pass an interface Imodel, without modifying the signature. Is there a base class for interfaces?
Also in the new mvc2 is there a way to avoid controllercontext altogether?
I'd only answer the first question - Why there's no common base interface for all interfaces ?
First of all, there's no common pre-defined base interface for all interfaces, unlike the System.Object case. Explaining this can get very interesting.
Let us assume, you could have a common interface for all interfaces in the system. That means, all interfaces will need to force their implementations to provide implementation-details for that common base interface. In general, interface are used to give specific special behaviors to their concrete implementation classes. Obviously you only want to define an interface when you only know what to do and don't know HOW to do that. So, if you let there be a common base interface for all interface and force the implementations to expect them to provide details of how to do it - why would you want to do it ? What common task each class should do that varies from one another ?
Lets look at the other side of the coin, why we have System.object as base class of any .Net type - It is simple it gives you some methods that have COMMON implementation for any .Net type and for those methods that it might vary from type-to-type they have made it virtual ex: .ToString()
There's possibly no assumption of any
system-wide interface method which is
virtual/abstract to all its
implementations.
One common practice of using Interface is say, defining a particular behavior to any type. Like I'd have an interface IFlyable which will give Fly() to all types that implement IFlyable. This way I can play with any Flyable object regardless of its inheritance hierarchy coming into picture. I can write a method like this..
public void FlyTheObject(IFlyable flyingObject)
{
flyginObject.Fly();
}
It does not demand anything from the object but the implementation of the Fly() method.
EDIT
Additionally, All interfaces will resolve to Object because interfaces cannot be instantiated. The object is always of a concrete class that can be instantiated. This class may or may not implement your interface but as we know, any .Net type is ultimately based to System.Object, so you will be able to take the instance into an object type regardless of the fact if it implements a particular interface or not.
No, there is no base class for interfaces. Nor there is base interface for interfaces.
As for your second question (and partly first one) - what are actually you trying to do?
There is no base class for interfaces, but you can pass any interface variable e.g:
private IEnumerable<int> myInterfaceVariable = new List<int>();
to your method because by definition anything that is stored in that variable must be an instance of a class that inherits from the interface - therefore it must be an object.
The following compiles fine:
public class InterfaceAsObject
{
private IEnumerable<int> myInterfaceVariable = new List<int>();
private void CallDoSomething()
{
DoSomething(myInterfaceVariable);
}
private void DoSomething(object input)
{
}
}
Re 1, there is no base interface, but if I understand you correctly, you can achieve what I think you want by just passing your object that implements IModel via the model parameter and cast (and check!) the parameter to IModel. I use 'as' and check for null.
If you don't need total flexibility, a better way of doing this is to define the interface that the model parameter must support. If the specific objects support derived interfaces (e.g. IDerivedModel : IModel) this will work too.
Look up a text-book on polymorphism.
Duplicate
What’s wrong with singleton?
Singletons: good design or a crutch?
Singleton: How should it be used
What is so bad about Singletons
You can find numerous reasons for using a Singleton over a Static class. But there must surely be some situations where it is better to use a static class before a Singleton. What are they?
You can use static class when:
1) all its methods are utilities (nice example - class Math)
2) you don't want to deal with preserving your instance from garbage collector (in applets), but I would better use singleton there
3) you are absolutely sure that it wouldn't become stateful in the future and you are sure that you will always need only one instance of that class
If you are using singleton and in one moment you realize that you need several instances then your singleton easily can be transformed to multitone, but you'll have a problem with static class
Having fought with the testability of consumers of static classes over the years I can honestly say that they are the work of evil minds. Seriously though, I'd use static classes for extention methods in C# but not really anywhere else.
If your class doesn't store any state, then use a Static class.
If it stores state and you require a single instance, then (maybe) use a Singleton.
Otherwise use a regular class.
Static class is better for when you don't need to change the implementation. With a Singleton, you can have an interface with various implementations. A Static class, can only be an implementation.
A singleton is a class of which only one instance can be instantiated, whereas there is no instance associated with a static method.
If you can implement the function you want with a single static method, then that is probably your best approach, because it is easier to implement. Consider extension methods - they are just static methods with syntactic sugar. If you can logically view the static method as a helper to an existing class, then it makes sense to use a static method.
On the other hand, if there is some sort of state involved in the functionality you are trying to achieve, then it is probably best to use a Singleton instead. The Singleton object can contain/manage its state and manage concurrent access/threading, whereas this becomes much more complicated with static classes and static methods. If you are using Singleton's in C#, I highly recommend reading Jon Skeet's article on proper Singleton implementation, which is available at http://www.yoda.arachsys.com/csharp/singleton.html .
Singleton's are more comparable to static classes than static methods. A big advantage that singletons have in this comparison is that they can implement interfaces and derive from base classes. This allows you to decouple their implementations from their interfaces. For example, if I have an interface IAccountService in my core assembly with a Singleton implementation, SingletonAspNetAccountService in my service layer, then I can inject the IAccountService into my UI layer with an IoC container, without requiring a dependency on my service layer in the UI layer. On the other hand, if I had a static Accounts class, then I would have to either create an adapter to the static class's methods or have a dependency on the service layer in my UI in order to access the static account functionality.
It's always where you don't actually need to pass the singleton instance anywhere.
For example, singleton will be useful if it implements some interface, you can't do it with a static class.
Remember, every Class instance is a singleton, managed by JVM.
So static class is a singleton.
I am looking at nServiceBus and came over this interface
namespace NServiceBus
{
public interface IMessage
{
}
}
What is the use of an empty interface?
Usually it's to signal usage of a class. You can implement IMessage to signal that your class is a message. Other code can then use reflection to see if your objects are meant to be used as messages and act accordingly.
This is something that was used in Java a lot before they had annotations. In .Net it's cleaner to use attributes for this.
#Stimpy77 Thanks! I hadn't thought of it that way.
I hope you'll allow me to rephrase your comment in a more general way.
Annotations and attributes have to be checked at runtime using reflection. Empty interfaces can be checked at compile-time using the type-system in the compiler. This brings no overhead at runtime at all so it is faster.
Also known as a Marker Interface:
http://en.wikipedia.org/wiki/Marker_interface_pattern
In java Serializable is the perfect example for this. It defines no methods but every class that "implements" it has to make sure, that it is really serializable and holds no reference to things that cannot be serialized, like database connections, open files etc.
In Java, empty interfaces were usually used for "tagging" classes - these days annotations would normally be used.
It's just a way of adding a bit of metadata to a class saying, "This class is suitable for <this> kind of use" even when no common members will be involved.
Normally it's similar to attributes. Using attributes is a preferred to empty interfaces (at least as much as FxCop is aware). However .NET itself uses some of these interfaces like IRequiresSessionState and IReadOnlySessionState. I think there is performance loss in metadata lookup when you use attributes that made them use interfaces instead.
An empty interface acts simply as a placeholder for a data type no better specified in its interface behaviour.
In Java, the mechanism of the interface extension represents a good example of use. For example, let's say that we've the following
interface one {}
interface two {}
interface three extends one, two {}
Interface three will inherit the behaviour of 'one' and 'two', and so
class four implements three { ... }
has to specify the two methods, being of type 'three'.
As you can see, from the above example, empty interface can be seen also as a point of multiple inheritance (not allowed in Java).
Hoping this helps to clarify with a further viewpoint.
They're called "Mark Interfaces" and are meant to signal instances of the marked classes.
For example... in C++ is a common practice to mark as "ICollectible" objects so they can be stored in generic non typed collections.
So like someone over says, they're to signal some object supported behavior, like ability to be collected, serialized, etc.
Been working with NServiceBus for the past year. While I wouldn't speak for Udi Dahan my understanding is that this interface is indeed used as a marker primarily.
Though I'd suggest you ask the man himself if he'd had thoughts of leaving this for future extension. My bet is no, as the mantra seems to be to keep messages very simple or at least practically platform agnostic.
Others answer well on the more general reasons for empty interfaces.
I'd say its used for "future" reference or if you want to share some objects, meaning you could have 10 classes each implementing this interface.
And have them sent to a function for work on them, but if the interface is empty, I'd say its just "pre"-work.
Empty interfaces are used to document that the classes that implement a given interface have a certain behaviour
For example in java the Cloneable interface in Java is an empty interface. When a class implements the Cloneable interface you know that you can call run the clone() on it.
Empty interfaces are used to mark the class, at run time type check can be performed using the interfaces.
For example
An application of marker interfaces from the Java programming language is the Serializable interface. A class implements this interface to indicate that its non-transient data members can be written to an ObjectOutputStream. The ObjectOutputStream private method writeObject() contains a series of instanceof tests to determine writeability, one of which looks for the Serializable interface. If any of these tests fails, the method throws a NotSerializableException.
An empty interface can be used to classify classes under a specific purpose. (Marker Interface)
Example : Database Entities
public interface IEntity {
}
public class Question implements IEntity {
// Implementation Goes Here
}
public class Answer implements IEntity {
// Implementation Goes Here
}
For Instance, If you will be using Generic Repository(ex. IEntityRepository), using generic constraints, you can prevent the classes that do not implement the IEntity interface from being sent by the developers.