How to Implement an Interface that Requires Duplicate Member Names? - .net-2.0

I often have to implement some interfaces such as IEnumerable<T> in my code.
Each time, when implementing automatically, I encounter the following:
public IEnumerator<T> GetEnumerator() {
// Code here...
}
public IEnumerator GetEnumerator1() {
// Code here...
}
Though I have to implement both GetEnumerator() methods, they impossibly can have the same name, even if we understand that they do the same, somehow. The compiler can't treat them as one being the overload of the other, because only the return type differs.
When doing so, I manage to set the GetEnumerator1() accessor to private. This way, the compiler doesn't complaint about not implementing the interface member, and I simply throw a NotImplementedException within the method's body.
However, I wonder whether it is a good practice, or if I shall proceed differently, as perhaps a method alias or something like so.
What is the best approach while implementing an interface such as IEnumerable<T> that requires the implementation of two different methods with the same name?
EDIT #1
Does VB.NET reacts differently from C# while implementing interfaces, since in VB.NET it is explicitly implemented, thus forcing the GetEnumerator1(). Here's the code:
Public Function GetEnumerator() As System.Collections.Generic.IEnumerator(Of T) Implements System.Collections.Generic.IEnumerable(Of T).GetEnumerator
// Code here...
End Function
Public Function GetEnumerator1() As System.Collections.Generic.IEnumerator Implements System.Collections.Generic.IEnumerable.GetEnumerator
// Code here...
End Function
Both GetEnumerator() methods are explicitly implemented, and the compile will refuse them to have the same name. Why?

You can use explicit interface implementation:
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator<T> GetEnumerator()
{
...
}

In Visual Basic, all interface implementations are explicit.
Interface mappings are defined by the Implements statement so you can name your interface implementation methods whatever you want. (Unlike C#, where the compiler infers which methods implement interfaces by matching their names and signatures.)
Changing the method name and visibility (as appropriate) is standard practice in VB. See Implementing Interfaces in VB.NET for a good overview.

You should be able to use Explicit Interface Implementations to create the two methods that have the same signature. Depending on what you are enumerating, I would just pass these calls through to an internal IEnumerable<T> such as a List or array.

Implementing the non-generic interface explicitly allows both methods to have the same name, and allows the non-generic version to be implemented in terms of the generic one. Along the lines of:
public class TestEnumerable : IEnumerable<int>
{
public IEnumerator<int> GetEnumerator()
{
// Type-safe implementation here.
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}

Related

Interface Injection chapter in DI

I just start learning what is Dependency Injection and InversionOfControll is. But I cant get one thing. The interface injection is onle when I define some interface where describe method what need to be realized. And that method gets instance of some class as parameter, and then In class what implements interface just describe body of this method ?
An interface is only a contract that defines what public members a class should implement. It does not control the actual implementation - you need a concrete class to do that.
// This is only a contract that defines what members
// all concrete types must implement.
public interface ISomeType
{
void DoSomething();
}
// This class implements the interface. Therefore, it must
// have all of the methods the contract specifies. In some
// languages, this can be done implicitly just by adding the
// member, but it usually must be public.
public class SomeType : ISomeType
{
public void DoSomething()
{
Console.WriteLine("Hello World");
}
}
When you make a class implement an interface it implicitly means that instances of the class can be cast to the interface type.
ISomeType x = new SomeType();
Dependency Injection takes advantage of this behavior. You typically define both the interface type and the concrete implementation together in a mapping.
container.For<ISomeType>().Use<SomeType>();
Then when a service is declared to take ISomeType as a constructor argument, the map is used to determine which concrete type to create an instance of.
public class SomeService : ISomeService
{
private readonly ISomeType someType;
public SomeService(ISomeType someType)
{
if (someType == null) throw new ArgumentNullException("someType");
this.someType = someType;
}
}
The recommended way is to allow the DI container to do this implicitly when your entire object graph is composed (in the Composition Root), but it is possible also to do it explicitly (and it makes a better example):
ISomeService = container.GetInstance<ISomeService>();
Assuming that the container was configured to map ISomeService to SomeService (like I showed before with ISomeType), this one line of code will create an instance of SomeService and automatically inject an instance of SomeType into its constructor.
It is difficult to see the point in a simple example, though. Dependency Injection is meant for complex applications with many types. It simplifies things when the application is complex, but when the application is simple it has a tendency to make things more complex.

Can one declare a static method within an abstract class, in Dart?

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.

What is better: public static Class with static methods or public Class with static methods?

Regarding class public class declaration, please look at these two pieces of code:
public class Helper
{
public static void CallMeganFox(string phoneNumber)
{ //...
and
public static class Helper
{
public static void CallMeganFox(string phoneNumber)
{ //...
What is better to use and why?
It's "better" in theory to make it explicit that this class is not supposed to be instantiated by making it static (second option), because it communicates intent¹.
However in such a simple case, from a practical perspective there will be exactly zero difference². Noone's going to look at this class and try to instantiate it.
¹ As Cody Gray points out, it can also help you catch mistakes earlier (e.g. forgetting to make a helper method static). While that viewpoint certainly has merit, again the practical difference is going to be negligible: the compiler would complain as soon as you tried to call the method statically in any case.
² Actually, this is not always true. For example, the C# compiler will not let you define extension methods in a non-static class -- not because it cannot, but because it wants to nudge you towards a "best practice".
static class cannot have non-static methods. If that's what you want - then use it.
More information can be found in this SO question and answers.

What is the base of all interfaces in .net, just like the base for all classes is the object

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.

Generic Wrapper Class possible?

On C# 3.0 and .NET 3.5, imagine there's an interface:
public interface INameable
{
string Name {get;}
}
and many immutable classes that implement the interface.
I would like to have a single extension method
public static T Rename<T>(this T obj) where T : INameable
{
...
}
that returns a wrapped instance of the original object with just the name changed and all other property reads and method calls routed to the original object.
How to get a generic wrapper class for this, without implementing it for all INameable implementing types? Do you think that's possible?
No, this isn't possible, unless T is constrained to be an interface or to be a class with all members virtual, and this constraint isn't possible to specify at compile time (though you could write a runtime check if you're happy with that approach).
The reason you cannot do it for arbitrary types is that if you take an object of type T then you must return an object that is assignable to T. If I pass an object that looks as follows...
public sealed class SomeClass : INameable
{
public string Name { get; }
public string Abc { get; }
}
...then there is no way you can create another type that is assignable to SomeClass. Not using Reflection.Emit or any other method, because the type is sealed.
However, if you're happy with the restrictions that I've mentioned then you could use something like the Castle DynamicProxy framework to create a type that proxies the passed in object and intercepts the calls to either forward or re-implement as appropriate.
Well, yes, it's possible, but it involves generating code in memory.
You can look at Reflection.Emit and here.
Note that it will involve a lot of code.
That is, if I assume I understand you correctly.
Here's what I think you're asking for:
SomeNameableObject a1 = new SomeNameableObject("ThisIsTheFirstName");
SomeNameableObject a2 = a1.Rename("ThisIsTheSecondName");
// a1 works, still has the name ThisIsTheFirstName
// a2 works, but everything is routed to a1,
// except for the name, which is ThisIsTheSecondName
Is that correct?