Extension methods on interfaces - c#

I have two interfaces IDto1 and IDto2. IDto2 inherits IDto1. Both interfaces are for DTOs and so I wish to keep "complex" code out of their implementations - I do this by putting a single extension method Initialize in a static class for each interface.
So I end up with the following types IDto1, IDto2, IDto1Extensions, IDto2Extensions.
I wish to have the Initialize extension method on both interfaces, but for each to have a different implementation.
In client code I want to use code like this:
(dto as IDto1).Initialize();
...and I'd like the relevant extension method to be invoked based on the resolved type of the dto variable at runtime.
Is this possible in C# and if not why not?
Edit:
Sorry, of course this:
(dto as IDto1).Initialize();
...will invoke the Initialize method on the IDto1 type. I meant that the dto variable would be passed in as an argument to a method, under which circumstances I believe the method would be chosen polymorphically given the inheritance hierarchy I specified earlier.
Thanks for all your answers.

What you are trying to achieve here is some sort of polymorphysm. Extension methods are static methods. In OOP polymorphysm is applicable only for instance methods.
An option could be to switch to abstract classes.

Looking at your statement:
(dto as IDto1).Initialize();
...and I'd like the relevant extension method to be invoked based on the resolved type of the dto variable at runtime.
The "resolved type" of the thing in brackets is precisely IDto1. It cannot be anything else, so that is what the compiler will work with. Indeed variables never change type (I assume you mean the object referred to by the variable's value).
In .NET 4.0 / C# 4.0, an option here for duck-typing might be an instance method and dynamic...
((dynamic)dto).Initialize();
...but to be honest I can't see why you can't just add your Initialize method to the interface and use polymorphism, since that sounds the closest to what you are trying to describe.

What you are trying to accomplish is not possible because extension methods are resolved at compile time, while in your case the actual type of the dto variable is known only at runtime.

If you want to make your code more dynamic you can define the class that you want in configuration file and use something like this
String className = ConfigurationManager.AppSettings["Interface"].ToString();
IDto1 dto = (IDto1)Activator.CreateInstance(Type.GetType(className));
In this sample I use the first line to get's the class name.
The second line create an instance of the Object.
Guilherme Ferreira
http://guilhermeferreira.wordpress.com/

This sounds like a job for an abstract base class.

Related

How to instruct Ninject to use a factory method for any requested subtype of a given type?

I have a base Dto type where I have several common logic and code (change notifications, validations, etc.). Due to technical reasons whenever I have to create an instance of a concrete DTO type like PersonDTO I have to use a factory method.
var personDto = Dto.Create<PersonDTO>();
// or a non-generic variant like
var personDto = Dto.Create(typeof(PersonDTO));
Now how could I ask Ninject to use this factory method whenever I need inject any Dto descendant? I mean something like
Bind<Dto>().ToMethod(ctx => Dto.Create(ctx.Request.Service));
but which could get applied to not only the base Dto requests but also to every request for any Dto descendant type.
I know I could probably use the conventions Ninject extension's "for all ..." kind of feature, but I'd rather like a way without yet another library if possible.
For every type which needs to be resolvable (IResolutionRoot.Get<SomeType>()), there needs to be a binding, for example:
Bind<Dto>().To..
Bind<DtoBla>().To..
except in case you'll do a binding with multiple types such as:
Bind<Dto,DtoBla>().To...
this overload is specifically useful when you want to bind multiple types to the same instance, for example if you want to have a singleton FooBar : IFoo, IBar resolve as IFoo and IBar.
Now in case you have to do a lot of very similar bindings, Ninject.Extensions.Conventions is just a library to make the task easier for you. You don't need to use it, you can also program type detection (using reflection) and binding creation yourself.
The reflection part has been covered many times over and over on stackoverflow, see for example:
Generating a list of child classes with reflection in .NET 3.5
Register all declared child classes of a class in C#
Get all derived types of a type
Search an assembly for all child types?
Of course, if you don't want to use Ninject.Extensions.Reflection, you can also just go look at its source code to see how it's done and copy the relevant parts! ;-)

When is it correct to create an extension method?

I have a piece of code like the following:
public class ActivityHelper
{
public void SetDate(IList<Activity> anActivityList)
{
foreach(Activity current in anActivityList)
{
current.Date = DateTime.Now;
}
}
//More methods, properties, fields, etc...
}
This could easily be converted to an extension method. For example:
public static void SetDate(this IList<Activity> aList)
{
foreach(Activity current in anActivityList)
{
current.Date = DateTime.Now;
}
}
The original function doesn't use any instance specific data or methods from the ActivityHelper class which makes it seem like it is in the incorrect place. Is this the correct time to write an extension method? What are the correct scenarios in which to create extension methods?
Brad Adams has written about extension method design guidelines:
CONSIDER using extension methods in any of the following scenarios:
To provide helper functionality relevant to every implementation of an interface, if said functionality can be written in terms of the core interface. This is because concrete implementations cannot otherwise be assigned to interfaces. For example, the LINQ to Objects operators are implemented as extension methods for all IEnumerable types. Thus, any IEnumerable<> implementation is automatically LINQ-enabled.
When an instance method would introduce a dependency on some type, but such a dependency would break dependency management rules. For example, a dependency from String to System.Uri is probably not desirable, and so String.ToUri() instance method returning System.Uri would be the wrong design from a dependency management perspective. A static extension method Uri.ToUri(this string str) returning System.Uri would be a much better design.
I think Extension methods are only appropriate if there is a compelling reason to make the method an extension method.
If the type is one you do not control, and the method should appear to be integral to the type, or if there is a compelling reason to not put the method directly on the type (such as creating an unwanted dependency) then an extension method could be appropriate.
Personally, if the expectation of the user of your API will already be to use the "ActivityHelper" class when working with collections of Activities, then I would probably not create an extension method for this. A standard, non-extension method will actually be a simpler API, since it's easily understood and discoverable. Extension methods are tricky from a usage standpoint - you're calling a method that "looks like" it exists somewhere other than where it actually exists. While this can simplify syntax, it reduces maintainability and discoverability.
In my experience extension methods work best when they:
Don't have side-effects (most of the extension methods my team wrote that have side-effects, we ended up removing because they caused more problems than they helped)
Offer functionality that applies to every possible instance or value of the type they're extending. (Again citing an example from my team, string.NormalizeUrl() is not appropriate because not all strings are even URLs anyway)
Well i usually create extension methods to help me write codes which have a smooth flow. Its generally depends upon the method you are creating.
If you feel that the method should have already been in framework and is too general then its okay to create an extension method for that.
But you need to first analyze that the class you are extending will always will be in state that your extension method can handle.
For Guidelines here to Brad's Article
http://blogs.msdn.com/b/brada/archive/2009/01/12/framework-design-guidelines-extension-methods.aspx
In essence, Extension Methods provide a more fluent style syntax for Helper methods. This translates into the ability to seemingly add functionality to types or all implementations of interfaces.
However, I generally steer away from declaring Extension Methods with a void returntype, as I feel the usefulness of this fluent style syntax, which allows you to compose statements, is negated when the method in question doesn't return anything.
However, I guess it can be handy to have your methods picked up by IntelliSense... :-)

Why is the 'this' keyword required to call an extension method from within the extended class

I have created an extension method for an ASP.NET MVC ViewPage, e.g:
public static class ViewExtensions
{
public static string Method<T>(this ViewPage<T> page) where T : class
{
return "something";
}
}
When calling this method from a View (deriving from ViewPage), I get the error "CS0103: The name 'Method' does not exist in the current context" unless I use the this keyword to call it:
<%: Method() %> <!-- gives error CS0103 -->
<%: this.Method() %> <!-- works -->
Why is the this keyword required? Or does it work without it, but I'm missing something?
(I think there must be a duplicate of this question, but I was not able find one)
Update:
As Ben Robinson says, the syntax to call extension methods is just compiler sugar. Then why can't the compiler automatically check the for extension methods of the current type's base types without requiring the this keyword?
A couple points:
First off, the proposed feature (implicit "this." on an extension method call) is unnecessary. Extension methods were necessary for LINQ query comprehensions to work the way we wanted; the receiver is always stated in the query so it is not necessary to support implicit this to make LINQ work.
Second, the feature works against the more general design of extension methods: namely, that extension methods allow you to extend a type that you cannot extend yourself, either because it is an interface and you don't know the implementation, or because you do know the implementation but do not have the source code.
If you are in the scenario where you are using an extension method for a type within that type then you do have access to the source code. Why are you using an extension method in the first place then? You can write an instance method yourself if you have access to the source code of the extended type, and then you don't have to use an extension method at all! Your implementation can then take advantage of having access to the private state of the object, which extension methods cannot.
Making it easier to use extension methods from within a type that you have access to is encouraging the use of extension methods over instance methods. Extension methods are great, but it is usually better to use an instance method if you have one.
Given those two points, the burden no longer falls on the language designer to explain why the feature does not exist. It now falls on you to explain why it should. Features have enormous costs associated with them. This feature is not necessary and works against the stated design goals of extension methods; why should we take on the cost of implementing it? Explain what compelling, important scenario is enabled by this feature and we'll consider implementing it in the future. I don't see any compelling, important scenario that justifies it, but perhaps there is one that I've missed.
Without it the compiler just sees it as a static method in a static class which takes page as it's first parameter. i.e.
// without 'this'
string s = ViewExtensions.Method(page);
vs.
// with 'this'
string s = page.Method();
On instance methods, 'this' is implicitly passed to each method transparently, so you can access all the members it provides.
Extension methods are static. By calling Method() rather than this.Method() or Method(this), you're not telling the compiler what to pass to the method.
You might say 'why doesn't it just realise what the calling object is and pass that as a parameter?'
The answer is that extension methods are static and can be called from a static context, where there is no 'this'.
I guess they could check for that during compilation, but to be honest, it's probably a lot of work for extremely little payoff. And to be honest, I see little benefit in taking away some of the explicitness of extension method calls. The fact that they can be mistaken for instance methods means that they can be quite unintuitive at times (NullReferenceExceptions not being thrown for example). I sometimes think that they should have introduced a new 'pipe-forward' style operator for extension methods.
It's important to note that there are differences between extension methods and regular methods. I think you've just come across one of them.
I'll give you an example of another difference: It's fairly easy to call an extension method on a null object reference. Fortunately, this is much more difficult to do with regular methods. (But it can be done. IIRC, Jon Skeet demonstrated how to do this by manipulating CIL code.)
static void ExtensionMethod(this object obj) { ... }
object nullObj = null;
nullObj.ExtensionMethod(); // will succeed without a NullReferenceException!
That being said, I agree that it seems a little unlogical that this is required to call the extension method. After all, an extension method should ideally "feel" and behave just like a normal one.
But in reality, extension methods are more like syntactic sugar added on top of the existing language than an early core feature that fits nicely into the language in all respects.
Because the extension method does not exist with the ViewPage class. You need to tell the compiler what you are calling the extension method on. Remember this.Method() is just compiler sugar for ViewExtensions.Method(this). It is the same way you can't just call an extention method within the middle of any class by the method name.
I am working on a fluent API and ran into the same issue. Even though I have access to the class I'm extending I still wanted the logic of each of the fluent methods to be in their own files. The "this" keyword was very unintuitive, users kept thinking the method was missing. What I did was make my class a partial class that implemented the methods I needed instead of using extension methods. I saw no mention of partials in the answers. If you have this question partials might be a better option.

C# - Is it possible to extend an existing built-in class with a new Interface

I am just learning C# and I have a problem now. :-)
In C++ I loved to use "const reference" as a parameter to avoid that
the called method changes my passed object.
I read somewhere that I can do sth. similar in C# by using Interfaces.
In the interface I would just put some "getters" to allow the method a readonly access
to my object.
Now guess, that I want to pass my C# method a built-in container like "List".
But I want to avoid that the method changes something in that list.
Just read only!
My first thought was:
- I create a new Interface called IMyOwnInterface, which uses the interface IList as well
My new interface IMyOwnInterface contains only "getters"
I change my method to sth. like that MyLittleMethod(IMyOwnInterface if)
Now the method "MyLittleMethod" can just see the "getters", which I put in my own interface and not the "setters" of IList
Is this possible?
Can someone give me a hint?
You want to use List.AsReadOnly.
http://msdn.microsoft.com/en-us/library/e78dcd75(VS.80).aspx
Yes, I believe that would work. Give it a shot, and let us know how it works :D
The answer is no:
IList does not implement IMyOwnInterface so you can't cast it.
IList list = ...
MyLittleMethod((IMyOwnInterface)list) // Compiler errror here
In this case you can use ReadOnlycollection:
IList list = ...
MyLittleMethod(new ReadOnlyCollection(list))
With interfaces, it's basically only possible through inheritance or with some proxy stuff (either explicit with an adapter class, via a RealProxy implementation, or with a library to do things like that, such as LinFu).
However, out of the box you can use delegates to do late-binding for single methods with matching signature.

C# Extension Methods Architecture Question

I recently asked this question:
Compiler error referencing custom C# extension method
Marc Gravell answer was perfect and it solved my problem. But it gave me something to think about...
If and Extension method must be placed on a Static Class and the method itself must be static, why can't we create a static Extension method?
I understand that the parameter marked as "this" will be used to allow access to an instance of the object we are extending. What I do not understand is why can't a method be created to be static... it just seems to me that this is a senseless limitation...
My question is: Why can't we create an extension method that will work as a static Method?
I expect the real answer is simply: there wasn't a good use-case. For instances, the advantage is that it enables a fluent-API over existing types (that don't themselves provide the logic) - i.e.
var foo = data.Where(x=>x.IsActive).OrderBy(x=>x.Price).First();
which enables LINQ:
var foo = (from x in data
where x.IsActive
order by x.Price
select x).First();
With static methods, this simply isn't an issue, so there is no justification; just use the static method on the second type.
As it is, extension methods are not properly object orientated - they are a pragmatic abuse to make life easier at the expense of purity. There was no reason to dilute static methods in the same way.
Because that feature doesn't exist in C#.
As a workaround, static methods can be implemented in another class and called through that class to provide the added functionality.
For example, XNA has a MathHelper class which ideally would have been static extensions to the Math class.
The community is asking if we think it's a good idea for C# 4.0
My thinking would be for compatibility - if you suddenly made all static methods extension methods with the need for the this operator you could inadvertently break code which now is overriding a normal method with an extension method.
The this parameter allows control and thus doesn't break compatibility.
Just an idea though.
First of all you would have to add yet another syntax to indicate you want to extend the static methods of the existing type. When extending syntax you really need a very good reason to do so.
Lets imagine I have a class called MyExts which allow me to add extension methods to MyClass. Why would:-
MyClass.DoSomethingExtra();
be better than
MyExts.DoSomethingExtra();
?

Categories

Resources