If for example, I declare an interface class whose actual class type will only be determined on runtime, and by using VisualStudio when I right click the method call and click "Go To Implementation" I can find 3 implementations from classes that inherits the interface.
How can I, using Roslyn, get the method's implementation syntax nodes/symbols?
You're looking for SymbolFinder.FindImplementationsAsync.
Just look at the code that implements Go To Implementation. There's several public APIs on the SymbolFinder type that give you overrides/implementations/derived types, and each give you symbols back. Most of the code in the feature is just figuring out which is the right method to call, with some extra filtering that's specific for the feature. For example, if you have a derived type that's got an abstract member, the core functions will return that method, but it's not an implementation in a meaningful way for the sake of the feature.
Related
Recently I found out that C# allows for
An interface can inherit from one or more base interfaces.
For instance, the IScreen in Caliburn.Micro does this in http://caliburnmicro.codeplex.com/SourceControl/latest#src/Caliburn.Micro/IScreen.cs
namespace Caliburn.Micro
{
public interface IScreen : IHaveDisplayName, IActivate, IDeactivate,
IGuardClose, INotifyPropertyChangedEx
{
}
}
I get why this is useful, as it implies that a class implementing IScreen also needs to implement the other interfaces.
But I wonder how the C# handles that compiler and run-time wise.
A little background/context of this question:
I come from a background where interfaces define a method-table, and that classes implementing interfaces have both their own method table, and pointers to the method tables of the interfaces they implement.
Sub questions swirling my mind stem from various multiple class inheritance discussions I had with people in the past, of which I think they apply to this case as well:
Having an interface be able to inherit from multiple base interfaces, how would the order of methods in that table be?
What if those interfaces have common ancestors: would those methods appear multiple times in the table?
What if those interfaces have different ancestors, but similar method names?
(I'm using the word methods here, implying that a property defined in an interface will have a get_ or set_ method).
Any insight into this is much appreciated, as well as tips on how to phrase this question better.
First of all, let's be explicit in saying that "interface inheritance" is not quite the same thing as class-based inheritance (and using the word "inheritance" for both is perhaps misleading).
That's because interfaces cannot be instantiated on their own, so the compiler/runtime pair does not have to keep track of how to make a virtual call for standalone interface types (e.g. you don't need to know how to call IEnumerable.GetEnumerator -- you just need to know how to call it on a specific type of object). That allows for handling things differently at compile time.
Now I don't actually know how the compiler implements "interface inheritance", but here's how it could be doing it:
Having an interface be able to inherit from multiple base interfaces,
how would the order of methods in that table be?
It's not necessary for the "derived" interface to have a method table that includes the methods from all of its ancestor interfaces because it does not actually implement any of them. It's enough for each interface type to only have a table of methods it defines itself.
What if those interfaces have common ancestors: would those methods
appear multiple times in the table?
Given the answer to the previous question, no. In the end a concrete type will only implement IFoo just once, regardless of how many times IFoo appears in the "hierarchy" of implemented interfaces. Methods defined in IFoo will only appear in IFoo's bookkeeping tables.
What if those interfaces have different ancestors, but similar method
names?
Again, no problem. You need appropriate syntax to tell the compiler "here's how to implement IFoo.Frob and here's IBar.Frob", but since methods of IFoo and IBar will be mapped in separate tables there are no technical issues.
Of course this leaves the question "how are methods dispatched at runtime?" unanswered. But it's not that difficult to imagine a possible solution: each concrete type C has pointers to one method table per interface it implements. When it's time to make a virtual method call the runtime looks at the concrete type, finds the table for the interface whose method is going to be called (the type of the interface is known statically) and makes the call.
I am unable to speak to how the official CLR does it.. but the Rotor distribution aggresively overlays common interface ancestors on top of one another in an objects vtable. It also allocates extra SLOTs into the concrete objects vtable where appropriate thereby reducing the need to jump from concrete type to interface vtable and then to the implementation.. the method offset is calculated at JIT time. If this optimization cannot be performed, then a single method can occupy the vtable more than once.
So the answer is (in regards to Rotor anyway), that it really is an implementation detail and any overlaying/optimizations etc are left completely up to what the compiler decides is best at the time it compiles the type.
I created a class called MostRecentStack<T> which is a stack that only keeps a certain number of items, dropping the ones at the bottom to make room for new ones. I'd like to have a variable that can store a reference to either a regular ("infinite") stack, or one of my custom type, depending on the circumstances, but C# defines no generic "stack" interface. Normally this wouldn't be a problem, but I'd like System.Collections.Generic.Stack<T> to implement the interface as well.
As long as a class provides the required members, is there any way to, in the interface definition, tell the compiler to consider a class as implementing the interface? I'd like to be able to do this without having to use as or other methods of typecasting.
The exact thing you're asking for isn't possible. However, something like should be very similar to what you want:
public class CompatibleStack<T> : System.Collections.Generic.Stack<T>, IYourStackInterface<T>
{
}
The CompatibleStack is functionally equivalent to System.Collections.Generic.Stack, except it now implements IYourStackInterface.
As long as System.Collections.Generic.Stack has all the right members to implement IYourStackInterface, this should compile fine. And you can pass a CompatibleStack around as an IYourStackInterface without any problems.
No, it is not possible to add new interface to existing class that you don't own. Options:
if you get instance of the class via some dependency injection controller you may be able to wrap class with proxy that will implement interface by calling matching methods.
you can simply derive from existing class and add interface (if it is not sealed) and start using your class.
in your particular case as Baldrick pointed out you can do reverse - derive from existing class and implement interface.
you can try to use dynamic to get some duck typing (as both classes will have matching methods) for some performance, readability and strong type cost.
Side note: in general C# does not support duck typing, but there is one case (foreach) where implementing interface is not strictly required - just having correct methods on collection is enough to support foreach.
I was trying NBuilder in my unit test. An excellent library. However, I could not explain the following structure of classes and interfaces.
In FizzWare.NBuilder namespace:
ISingleObjectBuilder
SingleObjectBuilderExtensions
In FizzWare.NBuilder.Implementation
IObjectBuilder`
ObjectBuilder
SingleObjectBuilderExtensions is simply a wrapper on IObjectBuilder.
The client code should usually use a class named Builder which has a static method that gives you ISingleObjectBuilder. You never need to instantiate any of the classes in client code.
Now, I dont get the point of the SingleObjectBuilderExtensions. Does it give any kind of design benefit? Why not the methods are directly in ISingleObjectBuilder specially when the two interfaces are in same namespace.
ISingleObjectBuilder is an interface; interfaces cannot provide implementation. That would mean that every implementation of ISingleObjectBuilder would need to provide the implementation.
However, in many cases, a method has a pre-defined behaviour, and just needs access to other members of the interface (i.e. just members of ISingleObjectBuilder), so there is no benefit in making each implementation provide this.
Additionally, it is not a good idea to add more members to an existing interface, since that would be a breaking change for all existing implementations.
Extension methods solve both of these issues:
the extension method will work for all implementations of ISingleObjectBuilder
it doesn't change the existing API, so all existing implementations will continue to be valid
Having it in the same namespace simply makes it convenient. It is a likely bet that any code using ISingleObjectBuilder already has a using directive importing that namespace; therefore, most code will already see the extension method in the IDE simply by pressing . in the IDE.
To add a concrete example, LINQ-to-Objects works on IEnumerable<T>. There are lots of IEnumerable<T> implementations. If each of them had to write their own First(...), FirstOrDefault(...), Any(...), Select(...) etc methods, that would be a huge burden - bot would provide no benefit as the implementations would be pretty much identical in most cases. Additionally, fitting this onto the interface retrospectively would have been disastrous.
As a side note: per-type versions of a method always take precedence over extension methods, so if (in the case of LINQ-to-Objects) you have a type that implements IEnumerable<T> (for some T), and that type has a .First() instance method, then:
YourType foo = ...
var first = foo.First();
will use your version, not the extension methods.
Extension methods are only syntactic sugar. They are normal static methods that work with public data the class they "extend" exposes.
There doesn't seem to be need for those extension methods to work with private fields and it also gives you ability to have interface instead of abstract class. And everyone knows interfaces are better choice than abstract classes.
And the reason for both to be in same namespace is to avoid declaring new namespace just to use the extension methods. How many times did it happen to you, that you tried to use LINQ only to notice there are no methods in intellisense or the code didn't compile. Reason being there was not System.Linq namespace included.
I have a generic interface:
public interface IUnauthorizedRequestRespondable<out T> where T:class
{
T GetResponseForUnauthorizedRequest();
}
(I'm not sure why Resharper recommended T is "out", but that's not the question).
In my scenario, the object returned by GetResponseForUnauthorizedRequest is always of the type that implements the interface.
So all the interface's implementations look like:
public class SignInReturnedObject : IUnauthorizedRequestRespondable<SignInReturnedObject>
(class name and the type in brackets are always the same).
Which seems a bit awkward - isn't there a neater way to tell the compiler that the interface's method returns the type it's a part of?
Thanks.
As far as I know, there is no way to do that currently in C#.
A theoretical side-note: The feature that would allow you to do this is called self types but that's not available in C#. The idea of the feature is that you have a special type that refers to the actual type of this, so if you had a special type named self, you could probably write something like:
public interface IUnauthorizedRequestRespondable {
self GetResponseForUnauthorizedRequest();
}
...and the actual type used in place of self when you have a class SignInReturnedObject implementing the interface would be SignInReturnedObject, but unfortunatelly, that's not
available in C# :-)
If the only way you want to use that template is in that manner, I would use:
public interface IUnauthorizedRequestRespondable<T> where T:IUnauthorizedRequestRespondable<T>
{
T GetResponseForUnauthorizedRequest();
}
This has the advantage of guaranteeing it isn't used in any other way.
The class declaration won't change, but I don't see anything as awkward in this myself. Considering that you are defining a relationship between the class and itself, any more concise form might be inadvisable.
Actually, that about sums it up. That is how the syntax works.
You can see it used in .NET itself with the IEquatable inteface--you are almost always comparing an object to itself, yet you always have to provide your own class name as a template parameter.
This is simply to provide flexibility such that you can compare to anything, not necessarily yourself.
You can create a nongeneric version and just use that but I think it is more trouble than it is worth
public interface ICastUnauthorizedRequestRespondable : IUnauthorizedRequestRespondable<SignInReturnedObject>
{
}
Since T can be any class (does not have to be the class you are implementing) you need to name your class.
public class SignInReturnedObject : IUnauthorizedRequestRespondable<ANYCLASS>
I feel like this should be very possible.
I have an interface, let's call it IJerry. Now, I have a class in variable x. That class implements IJerry perfectly. The thing is, that class does not ever reference IJerry. It just happens to have a perfect, compliant signature with IJerry.
Make sense? Let's say you create a class called MyClass that implements INotifyPropertyChanged. Then you delete the MyClass : INotifyPropertyChanged declaration from the class but you LEAVE the implementation inside the class.
Is there a way to determine if the class "implements" an interface even if it does not make an explicit reference to it?
Not easily.
You would have to read the fields, method, and properties of the interface using reflection, and then check if the class has them (again using reflection)
Alternately, if you are using C#4, you could just forget about IJerry, and put MyClass in a dynamic variable, and then you C# figure out at run-time for it has the methods being called.
There's a lot more to implementing an interface than meets the eye. For one, implementation methods are virtual, even though you don't use that keyword. In fact, you're not allowed to use that keyword. For another, the compiler rearranges the methods to match the method table layout of the interface. Removing the inherited interface from the declaration is guaranteed to make the result incompatible. The methods won't be virtual anymore.
What you are pursuing is called 'dynamic dispatch'. Implemented in the DLR and integrated into .NET 4.0 and the C# 4.0 language. Re-inventing the System.Reflection code and making it efficient is a major undertaking.
You would have to use reflection to see if x had methods that matched the ones on IJerry. The real question is, what are you going to do with the answer? Prior to version 4, C# doesn't support "duck typing", so in order to use your class where an IJerry is required you have to write adapter code.