I have a C# project with a generic interface
public interface IMyFoo<T> { void DoSomething(T instance); }
I also have a C# project with an interface that inherits from several IMyFoos
public interface IMyBar : IMyFoo<Type1>, IMyFoo<Type2> { ... }
Everything works fine in C# land (including the scenario below which doesn't work in VB).
I have a VB .NET project that references this C# library.
I have an instance of IMyBar and try to use as follows:
Dim instance as MyType1 = ...
Dim bar as IMyBar = ...
bar.DoSomething(instance) ' This generates a compile error:
' 'DoSomething' is ambiguous across the inherited interfaces 'IMyFoo(Of MyType1)' and 'IMyFoo(Of MyType2)'.
What's up? I can DirectCast like this and it works fine...but I'd REALLY rather not
DirectCast(bar, IMyFoo(Of MyType1)).DoSomething(instance)
You're probably going to have to cast:
Unlike other types, which only derive from a single base type, an interface may derive from multiple base interfaces. Because of this, an interface can inherit an identically named type member from different base interfaces. In such a case, the multiply-inherited name is not available in the derived interface, and referring to any of those type members through the derived interface causes a compile-time error, regardless of signatures or overloading. Instead, conflicting type members must be referenced through a base interface name.
Just to go into further details, the reason VB doesn't directly support what you are doing is because what you showed is just a special case of a class implementing two interfaces with the same method. Whenever VB sees this it forces a cast to make it explicit which one you are intending to use. The VB designers decided that this would make code less error-prone. C# goes further and assumes that you know what you are doing and lets you make that call. You can make C# get the same basic error by using the more generic case of two interfaces with the same method:
public interface IMyFoo1 { void DoSomething(string instance); }
public interface IMyFoo2 { void DoSomething(string instance); }
public interface IMyBar : IMyFoo1, IMyFoo2 { }
public class MyTestClass : IMyBar
{
//Explicit interface declaration required
void IMyFoo1.DoSomething(string instance) { }
void IMyFoo2.DoSomething(string instance) { }
}
string s = "";
IMyBar bar = new MyTestClass();
bar.DoSomething(s);//The call is ambiguous between the following methods or properties...
Related
In C#, an interface is a bit different from C++ with pure virtual functions or Java.
In C# methods in an interface don't act like virtual functions, unlike other major compile-languages, which means we can not override them.
interface IMyInterface
{
void Foo();
}
class Root : IMyInterface
{
public void Foo() { ... } // OK.
}
class Child : Root
{
public void Foo() { ... } // Not overrided.
]
So I assume that in that case the interface doesn't even contain vtable either.
Without that or anything that points to the function address, how do the interfaces in C# know where the designated methods to invoke are, internally?
The reason you cannot override 'Foo' is that 'Root' has not marked it as virtual. If you mark it as virtual, it works like any other virtual method, and can be overriden as required from Child. You can think of C# as sealing interface method implementations by default. Well, anything is in fact sealed by default in C# (except finalizers of course..).
Contrast this with a language like Java, where all instance and nonprivate functions are by default virtual.
This doesn't answer how interfaces work internally, but that is related to the CLR, not to C#. Basically the CLR generates code specific to every call site of interface functions which looks up the address of the interface function it should be calling based on the object (much like normal virtual dispatch). Of course a static call can be performed when the function is not virtual, as in your case (if we have a reference to Child or Root).
you're confusing interfaces with inheritance..
in your example above Root implements IMyInterface and exposes the traits defined in IMyInterface. on a completely different note Child inharits all of Root's implementation and most expose a super-set of the same traits.
in fact you could override Foo in Child, and also reimplement if you use explisit interface implementation (name it IMyInterface.Foo)
so you can:
interface IMyInterface
{
void Foo();
}
class Root : IMyInterface
{
public virtual void Foo() { }
}
class Child : Root
{
public override void Foo() { }
void IMyInterface.Foo() { }
}
regarding :
Without that or anything that points to the function address, how do
the interfaces in C# know where the designated methods to invoke are,
internally?
your answer is here:
http://msdn.microsoft.com/en-us/magazine/cc163791.aspx#S12
or in the very recommended book CLR via C#
the important thing to remember is : in .Net interfaces have nothing to do with inheritance
This has been asked before, but I could not get clarity from that answer, that's why I ask again...
Let's use two examples:
class implements interface
class extends an abstract class
My feeling is that with respect to the override keyword, both samples must behave identically. What is the desired goal of override? To prevent a method being dropped in a superclass or interface without being changed in all subclasses or implementing classes. So a compile time code consistency check.
In this C# code, compiling results in error: '....RepositoryContext.getXmlDoc()': no suitable method found to override:
interface IRepositoryContext
{
XmlDocument getXmlDoc();
}
class RepositoryContext : IRepositoryContext
{
private readonly XmlDocument gXmlDoc = new XmlDocument();
public override XmlDocument getXmlDoc() // does not compile
{
return gXmlDoc;
}
}
Whereas in this C# code, compilation works without any errors or warnings:
abstract class RepositoryContextBase
{
public abstract XmlDocument getXmlDoc();
}
class RepositoryContext : RepositoryContextBase
{
private readonly XmlDocument gXmlDoc = new XmlDocument();
public override XmlDocument getXmlDoc()
{
return gXmlDoc;
}
}
Is it a valid assumption that this should not work identically, or is there a way around this, or...?
The override modifier is defined thus:
The override modifier is required to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event.
http://msdn.microsoft.com/en-us/library/ebca9ah3.aspx
The override keyword specifies that the method overrides an existing method implementation, which is why you don't need to specify it when you're implementing an interface directly - there is no such method to override; you're the first to implement it.
When you use the override keyword, you're essentially saying "for this class, call this method instead of the base method." This obviously doesn't apply when there is no such base method (e.g. when you are directly implementing an interface).
For virtual or abstract methods from classes, you need to insert the override keyword or it won't work at all.
For interfaces, there is no equivalent.
However, interface implementations must implement all of their base methods, so forgetting a method will usually give you a compiler error.
This makes it less important.
In the first example it's an interface you're implementing. You can't override something when you're the only implementer in the inheritance chain.
In the second example you've inherited from a concrete implementation and stated that you want to implement the abstract member and the syntax for that (albeit not literally an override as much as an implementation) is the override keyword. However, you are in fact overriding the chain you're a part of because you're implementing it.
So think of the override keyword more in relation to the fact that you're ensuring your implementation gets called instead of the base class when it's called on an instance of the inheritor.
This too explains why you must explicitly call base.Member() inside the override because you've overriden the chain.
Another OO concept to remember is that the same effect can be achieve on methods that aren't abstract or virtual. Members can in fact be hidden and you don't have to specify them with the new keyword.
With that being said it should help abstract for you the idea that these are very much just language features or maybe better said it's just syntax.
In your first example you are implementing an interface. In this case you do not have to specify the override keyword, simply remove it.
Seems like you have a misconception regarding interface implementation vs. inheritance.
Interface implementations are completely different from inheritance. With an interface, you statically (i.e. at compile time) enforce the presence of certain method signatures. Therefore, any keywords like override or the like are just plain wrong in such a context.
Inheritance on the contrary is causing runtime polymorphism through a virtual method table (basically a list of method adresses).
You can see this also from the fact that, in C#, you can implement as many interfaces as you like, whereas multiple inheritance is forbidden.
The reason is that there is a fundamental difference between implementing an interface and overriding a method.
In order to fully implement an interface, you have to provide implementations for all of methods and/or properties but those implementations do not necessarily have to be overrideable in turn. The compiler wants you to be very specific about your intentions when you create a method, because you may have one of a range of behaviours in mind, and it wants to be sure which one you mean.
The override keyword means "I am overriding the base class' implementation with this one". If when implementing an interface, there is no base implementation, then it doesn't apply. You use virtual to indicate an overrideable method with no base implementation, and omit both override and virtual otherwise.
So given this interface:
interface IFoo
{
void Bar();
}
This class implements that interface, and permits classes to inherit from it in turn and override that implementation (since unlike in e.g. Java, methods in C# are not virtual by default):
class Foo : IFoo
{
public virtual void Bar() { ... } // compiles
}
class DerivedFoo : Foo
{
public override void Bar() { ... } // compiles, and may choose to call base.Bar()
}
Whereas this class implements that interface, and does not permit overrides:
class Foo : IFoo
{
public void Bar(); // compiles
}
class DerivedFoo : Foo
{
public override void Bar() { ... } // does NOT compile; Foo.Bar() is not virtual (overrideable)
}
There are in fact more possiblities than that, including:
You can create an abstract base class which implements an interface, but only provide abstract implementations for some/all methods.
You can explicitly implement an interface method
You can seal an overriding method to prevent further overrides
You can create a new method with the same name which is unrelated to the base class' method of that name
There are more details on MSDN.
If you aren't specific enough for the compiler, it will warn you or throw an error.
Update
The reason the compiler complains in the second example above, is that you will not get polymorphic behaviour. That is, if someone has a reference to Foo and calls Bar(), they will get Foo's implementation, not DerivedFoo's. This is because Bar.Foo is not in the virtual method table. Put another way, in C#, the default when compared to Java is that all methods are final unless you say otherwise.
From your comments it sounds like you're trying to get a warning or error in the case where, in my first example above, you then change IFoo by removing the Bar method entirely. (Obviously if you just change the method signature, you'll get a suitable compile error as you'd hope.)
You can achieve this by explicitly implementing the method:
class Foo : IFoo
{
void IFoo.Bar() { ... }
}
Then if the interface changes, you will get a compile error. However, this means derived classes can no longer override Foo's implementation; if you want that behaviour as well, you need:
class Foo : IFoo
{
void IFoo.Bar() { ... }
protected /* or public */ virtual void Bar()
{
IFoo foo = this; // declare rather than cast, to get compile error not runtime exception
foo.Bar();
}
}
You will still get compile errors if you remove the method, both from your explicit and other implementation.
Bear in mind that the explicit implementation is only available to callers with a reference to an IFoo, not a Foo. But if as in the above code you do add a public method which, for example, delegates to the explicit IFoo implementation, that won't be a problem (and it doesn't have to be virtual unless you want it overrideable).
This is an approach that works; whether it's overkill is a matter of taste, but I can see the merit in removing redundant code as part of refactoring, provided the classes are not public and/or not used outside your assembly. However instead of factoring code in this fashion I'd recommend using a tool such as ReSharper which will warn you about unused methods.
Implementing Interface just provide the skeleton of the method. If we know the exact signature line of that method, in this case
what is the requirement to implement Interface?
This is the case in which Interface has been implemented
interface IMy
{
void X();
}
public class My:IMy
{
public void X()
{
Console.WriteLine("Interface is implemented");
}
}
This is the case in which Interface has not been implemented
public class My
{
public void X()
{
Console.WriteLine("No Interface is implemented ");
}
}
My obj = new My();
obj.X();
Both the approaches will produce the same result.
what is the requirement to implement Interface?
The purpose of interfaces is to allow you to use two different classes as if they were the same type. This is invaluable when it comes to separation of concerns.
e.g. I can write a method that reads data from an IDataReader. My method doesn't need to know (or care) if that's a SqlDataReader, and OdbcDataReader or an OracleDataReader.
private void ReadData(IDataReader reader)
{
....
}
Now, lets say I need that method to process data coming from a non-standard data file. I can write my own object that implements IDataReader that knows how to read that file, and my method again, neither knows nor cares how that IDataReader is implemented, only that it is passed an object that implements IDataReader.
Hope this helps.
You can write multiple classes that implement an interface, then put any of them in a variable of the interface type.
This allows you to swap implementations at runtime.
It can also be useful to have a List<ISomeInterface> holding different implementations.
There are two purposes of inheritance in .net:
Allow derived classes to share the base-class implementations of common functionality
Allow derived-class objects to be substituted for base-class objects anywhere the latter would be accepted.
Unlike some languages (C++, for example) which allow multiple inheritance, .net requires every class to have precisely one parent type (Object, if nothing else). On the other hand, sometimes it's useful to have a class be substitutable for a number of unrelated types. That's where interfaces come in.
An object which implements an interface is substitutable for an instance of that declared interface type. Even though objects may only inherit from one base type, they may implement an arbitrary number of interfaces. This thus allows some of the power of multiple inheritance, without the complications and drawbacks of full multiple-inheritance support.
You've provided a very basic example, which is probably why you're having trouble understand why. Examine something like this:
public interface IDbColumn
{
int domainID { get; set; }
}
public static IEnumerable<T> GetDataByDomain<T>(
IQueryable<T> src) where T:IDbColumn
{
string url = HttpContext.Current.Request.Url.Host;
int i = url == "localhost" ? 1 : 2;
return src.Where(x => x.domainID == i|| x.domainID == 3);
}
domainID is a physical column in every table that will reference this method, but since the table type isn't known yet there's no way to have access to that variable without an interface.
Heres simple example wich helped me to understand interfaces:
interface IVehicle
{
void Go();
}
public class Car:IVehicle
{
public void Go()
{
Console.WriteLine("Drive");
}
}
public class SuperCar:IVehicle
{
public void Go()
{
Console.WriteLine("Drive fast!!");
}
}
IVehicle car = new Car();
car.Go(); //output Drive
car = new SuperCar();
car.Go(); //output Drive fast!!
Say you have three classes, A, B, C.
A needs to accept an argument. Either B or C can be passed through.
The best way to do this is create an interface that B and C share
Well interfaces are not meant to be used with just one class, they are used accross many classes to make sure that they contain a set of methods.
a good way to visualize it is to think about driver abstraction, being able to run 1 query that can be interoperated by several different database servers.
interface DatabaseDriver
{
public function connect(ConnectionDetails $details){}
public function disconnect(){}
public function query(Query $query){}
public function prepareQuery(SQLQuery $query){}
}
and then your actual drivers would use the interface so that the database object can be assured that that the selected driver is able to perform the tasks required.
class MySqlDriver extends Database implements DatabaseDriver{}
class AccessDriver extends Database implements DatabaseDriver{}
class MsSqlDriver extends Database implements DatabaseDriver{}
hope this helps.
Note: Code in PHP
I have a C# class hierarchy with a common base type and two derived types. I want to declare an abstract method on the base class something like this :
public abstract IEnumerable<T> GetSiblings<T>() where T : MyBaseClass
... and I want this method to be implemented in the derived classes such that T is the type of that derived type, for each of the derived types, ie, in derived class A:
public override IEnumerable<A> GetSiblings<A>() { ... }
... and in derived class B ...
public override IEnumerable<B> GetSiblings<B>() { ... }
Put another way, each derived class must implement the method so that it returns an IEnumerable of items of the same type. Is there any way to implement this in C# ?
Well, you can hardly call a method generic if it only accepts a parameter of a single type, and your method signatures will have different return types which isn't allowed. Why don't you define an interface for all of these classes and simply return an IEnumerable<IMyClass>?
You can't do this because the return types are different. Simple as that. The reason is if you create an instance of A and stuff it into your base class(cast it) then the return type will be wrong.
You might be able to to use new instead but that might break your hierarchy.
This is not supported by the type system. It's a common enough problem, represented often as
class Animal<T> where T : Animal<T> { }
class Cat : Animal<Cat> { } // what you desire
class Dog : Animal<Cat> { } // what is possible yet not desired
But not a problem that has as yet been acted upon by the appropriate parties (be it the framework providers or C# team, not sure who).
Until it passes the critical "worth it" test as determined by costs (and opportunity costs) versus benefits, you'll have to work around it.
I found the solution. Apparently in C# 4.0, generic parameter types can be covariant, so what I've posted above will work. C# 3.5 or lower, and it doesn't work. Took a lot of Googling.
Is there a way?
I need all types that implement a specific interface to have a parameterless constructor, can it be done?
I am developing the base code for other developers in my company to use in a specific project.
There's a proccess which will create instances of types (in different threads) that perform certain tasks, and I need those types to follow a specific contract (ergo, the interface).
The interface will be internal to the assembly
If you have a suggestion for this scenario without interfaces, I'll gladly take it into consideration...
Not to be too blunt, but you've misunderstood the purpose of interfaces.
An interface means that several people can implement it in their own classes, and then pass instances of those classes to other classes to be used. Creation creates an unnecessary strong coupling.
It sounds like you really need some kind of registration system, either to have people register instances of usable classes that implement the interface, or of factories that can create said items upon request.
You can use type parameter constraint
interface ITest<T> where T: new()
{
//...
}
class Test: ITest<Test>
{
//...
}
Juan Manuel said:
that's one of the reasons I don't understand why it cannot be a part of the contract in the interface
It's an indirect mechanism. The generic allows you to "cheat" and send type information along with the interface. The critical thing to remember here is that the constraint isn't on the interface that you are working with directly. It's not a constraint on the interface itself, but on some other type that will "ride along" on the interface. This is the best explanation I can offer, I'm afraid.
By way of illustration of this fact, I'll point out a hole that I have noticed in aku's code. It's possible to write a class that would compile fine but fail at runtime when you try to instantiate it:
public class Something : ITest<String>
{
private Something() { }
}
Something derives from ITest<T>, but implements no parameterless constructor. It will compile fine, because String does implement a parameterless constructor. Again, the constraint is on T, and therefore String, rather than ITest or Something. Since the constraint on T is satisfied, this will compile. But it will fail at runtime.
To prevent some instances of this problem, you need to add another constraint to T, as below:
public interface ITest<T>
where T : ITest<T>, new()
{
}
Note the new constraint: T : ITest<T>. This constraint specifies that what you pass into the argument parameter of ITest<T> must also derive from ITest<T>.
Even so this will not prevent all cases of the hole. The code below will compile fine, because A has a parameterless constructor. But since B's parameterless constructor is private, instantiating B with your process will fail at runtime.
public class A : ITest<A>
{
}
public class B : ITest<A>
{
private B() { }
}
Juan,
Unfortunately there is no way to get around this in a strongly typed language. You won't be able to ensure at compile time that the classes will be able to be instantiated by your Activator-based code.
(ed: removed an erroneous alternative solution)
The reason is that, unfortunately, it's not possible to use interfaces, abstract classes, or virtual methods in combination with either constructors or static methods. The short reason is that the former contain no explicit type information, and the latter require explicit type information.
Constructors and static methods must have explicit (right there in the code) type information available at the time of the call. This is required because there is no instance of the class involved which can be queried by the runtime to obtain the underlying type, which the runtime needs to determine which actual concrete method to call.
The entire point of an interface, abstract class, or virtual method is to be able to make a function call without explicit type information, and this is enabled by the fact that there is an instance being referenced, which has "hidden" type information not directly available to the calling code. So these two mechanisms are quite simply mutually exclusive. They can't be used together because when you mix them, you end up with no concrete type information at all anywhere, which means the runtime has no idea where to find the function you're asking it to call.
So you need a thing that can create instances of an unknown type that implements an interface. You've got basically three options: a factory object, a Type object, or a delegate. Here's the givens:
public interface IInterface
{
void DoSomething();
}
public class Foo : IInterface
{
public void DoSomething() { /* whatever */ }
}
Using Type is pretty ugly, but makes sense in some scenarios:
public IInterface CreateUsingType(Type thingThatCreates)
{
ConstructorInfo constructor = thingThatCreates.GetConstructor(Type.EmptyTypes);
return (IInterface)constructor.Invoke(new object[0]);
}
public void Test()
{
IInterface thing = CreateUsingType(typeof(Foo));
}
The biggest problem with it, is that at compile time, you have no guarantee that Foo actually has a default constructor. Also, reflection is a bit slow if this happens to be performance critical code.
The most common solution is to use a factory:
public interface IFactory
{
IInterface Create();
}
public class Factory<T> where T : IInterface, new()
{
public IInterface Create() { return new T(); }
}
public IInterface CreateUsingFactory(IFactory factory)
{
return factory.Create();
}
public void Test()
{
IInterface thing = CreateUsingFactory(new Factory<Foo>());
}
In the above, IFactory is what really matters. Factory is just a convenience class for classes that do provide a default constructor. This is the simplest and often best solution.
The third currently-uncommon-but-likely-to-become-more-common solution is using a delegate:
public IInterface CreateUsingDelegate(Func<IInterface> createCallback)
{
return createCallback();
}
public void Test()
{
IInterface thing = CreateUsingDelegate(() => new Foo());
}
The advantage here is that the code is short and simple, can work with any method of construction, and (with closures) lets you easily pass along additional data needed to construct the objects.
Call a RegisterType method with the type, and constrain it using generics. Then, instead of walking assemblies to find ITest implementors, just store them and create from there.
void RegisterType<T>() where T:ITest, new() {
}
I don't think so.
You also can't use an abstract class for this.
I would like to remind everyone that:
Writing attributes in .NET is easy
Writing static analysis tools in .NET that ensure conformance with company standards is easy
Writing a tool to grab all concrete classes that implement a certain interface/have an attribute and verifying that it has a parameterless constructor takes about 5 mins of coding effort. You add it to your post-build step and now you have a framework for whatever other static analyses you need to perform.
The language, the compiler, the IDE, your brain - they're all tools. Use them!
No you can't do that. Maybe for your situation a factory interface would be helpful? Something like:
interface FooFactory {
Foo createInstance();
}
For every implementation of Foo you create an instance of FooFactory that knows how to create it.
You do not need a parameterless constructor for the Activator to instantiate your class. You can have a parameterized constructor and pass all the parameters from the Activator. Check out MSDN on this.