I dont have much experience of using these 2 ways to extend a class or create extension methods against a class. By looking others work, I have a question here.
I saw pe
If you choose the Partial Class route but find you are repeating the same code, switch to Extension Methods.
For example, i have many generated classes with methods which return IEnumerable<Track>
data. I want to extend each class somehow to give me the option of receiving the data in the format IEnumerable<MediaItem>
.
I have a general requirement here to transform IEnumerable<Track>
data to IEnumerable<MediaItem>
. In this case, rather than writing multiple partial class
methods an extension method works best:
public static class ExtensionMethods
{
public static IEnumerable<MediaItem> ToMediaItems(this IEnumerable<Track> tracks)
{
return from t in tracks
select new MediaItem
{
artist = t.Artist,
title = t.Title,
// blah blah
};
}
}
This gives me the following options:
var data = Playlist.Tracks.ToMediaItems();
var data = Podcast.Tracks.ToMediaItems();
// etc..
you can use partial classes in a project you're developing, while extension methods could be used also to extend projects you don't have source code too..
A partial class is useful when you want to extend a generated class. This way you can write your code in one file, and then when/if the other 'part' of your class needs to be re-generated, it can be done safely, as that code file hasn't changed.
Partial works only if both files are in the same project, and you can access private and protected members of that class.
Extension methods are just static methods, and can't access private members.
So if you want to access private and protected members, only way you have is partial, if no, answer to the question, should the method you want to add be visible everywhere you want to use class? if yes, use partial, if no, it's some kind of extension, use extension methods.
By the way, if the first class is not generated by some tool, you can write your function there except of using partial ;)
hope this helps
Partial classes should be used in code generation scenarios.
Since the generated file might get overwritten at any time, one uses partial classes to write into the non-generated file.
Additionally, partials will only work if they are part of the same assembly - they cannot cross assembly boundaries.
If these are not your constraints, you can and should use extension methods - of course, after considering other possibilities such as inheritance and composition for suitability.
You can use extension methods on a NULL instance but not instance methods (of partial classes or otherwise). This is a consequence of extension methods actually being static.