473,230 Members | 1,574 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,230 software developers and data experts.

Static generic extension method

Extension methods are made for use with instances. I'd like to "misuse" them
as static methods, too. Let me tell you my ambition:

I use an extension method to serialize objects somehow like this:

MyObject obj = new MyObject();
obj.ToXmlFile("some directory\\some file.xml");

The method "ToXmlFile" is defined elsewhere far apart from MyObject to work
for all objects:

public static void ToXmlFile<T>(this T obj, string path)
{
//do the right thing
}

And of course there is another method being a "classic" static method that
reads the XML file and deserializes its contents:

public static T FromXmlFile<T>(string path)
{
//do the right thing the other way round
}

That method is called:

MyObject obj = MyXmlSerializerClass.FromXmlFile<MyObject>("somewh ere");

Now my question is: Can you think of a possibility to define "FromXmlFile"
in some way that allows me to call it more convenient? i.e.:

MyObject obj = MyObject.FromXmlFile("somewhere");

A solution that does also work for 3rd party objects whose code I can't
manipulate? i.e.:

TheirObject obj = TheirObject.FromXmlFile("somewhere");

Something one might call "static extension method"?
I'd really appreciate any hints!

Thanks in advance,
Steffen
Jun 27 '08 #1
4 3325
Steffen Bobek wrote:
Extension methods are made for use with instances. I'd like to "misuse" them
as static methods, too.
Short of creating your own C# variant, you can't, end of story.
Let me tell you my ambition:
OK, so maybe it's not.
I use an extension method to serialize objects somehow like this:

MyObject obj = new MyObject();
obj.ToXmlFile("some directory\\some file.xml");

The method "ToXmlFile" is defined elsewhere far apart from MyObject to work
for all objects:

public static void ToXmlFile<T>(this T obj, string path)
{
//do the right thing
}
Hmm. This sounds far inferior to having a class whose job it is to
serialize. Something like, I don't know, XmlSerializer. Static methods are
quite inflexible, and serialization is one of those things where relying on
the One True Approach for everything will probably get you in trouble.

Even if you don't like XmlSerializer, the basic approach of that is sound:
use an object to serialize. Creating an object is more flexible than calling
a static method (as there are more ways of doing the former than doing the
latter). That object can also reuse any run-time structures that need to be
built for serializing a given type. Doing such caching for a static method
will just involve creating similar objects in the background, at increased
bookkeeping overhead.

Aside from that, using an extension method for this just seems wrong.
Extension methods are supposed to provide additional functionality for
specific types. Defining one that works on any T is like extending Object
itself, and that's pretty far-reaching. It makes it harder to reason about
classes and objects in terms of responsibilities: there are no classes or
objects responsible for serialization in your model, it's actually this one
method that's doing the work -- even thought it *appears* as if individual
objects are responsible.
And of course there is another method being a "classic" static method that
reads the XML file and deserializes its contents:

public static T FromXmlFile<T>(string path)
{
//do the right thing the other way round
}

That method is called:

MyObject obj = MyXmlSerializerClass.FromXmlFile<MyObject>("somewh ere");

Now my question is: Can you think of a possibility to define "FromXmlFile"
in some way that allows me to call it more convenient? i.e.:

MyObject obj = MyObject.FromXmlFile("somewhere");

A solution that does also work for 3rd party objects whose code I can't
manipulate? i.e.:

TheirObject obj = TheirObject.FromXmlFile("somewhere");

Something one might call "static extension method"?
C# just doesn't support that, and there's really nothing to be gained from
it. Extension methods are a double-edged sword as it is: they're bad for
readability as it's not immediately clear where a method is coming from, and
they're good for readability as they preserve traditional O-O semantics in
absence of developer clairvoyance.

Static methods on classes are not traditional O-O semantics, though, and the
minor readability gain they offer in a scenario like this doesn't weigh
against the drawbacks extension methods have.

--
J.
Jun 27 '08 #2
Jeroen, thank you for your reply.

Let me put my approach straight. I think every developer's goal is to write
easily readable and understandable code. And to me this is (amongst others)
excellently done by extension methods, because you write significantly less
code and separate your code by functionality at the same time (in my case
XML serialization is coded in one place only).

Since XmlSerializer itself seems to me like a giant static method (you can
put in any object to have it serialized to XML), I didn't see something
wrong to embed it into an extension method that provides exactly this
funcionality to any object.

My implementation works really fine. It's just the deserialization call that
annoys me, because I imagined the shorter option "AnyObject obj =
AnyObject.FromXmlFile(path)" (to get back to my approach).

But I understand that it's impossible to implement "static extension
methods", sadly. Thanks for your note about that!

Steffen
"Jeroen Mostert" <jm******@xs4all.nlschrieb im Newsbeitrag
news:47***********************@news.xs4all.nl...
Steffen Bobek wrote:
>Extension methods are made for use with instances. I'd like to "misuse"
them as static methods, too.

Short of creating your own C# variant, you can't, end of story.
>Let me tell you my ambition:
OK, so maybe it's not.
>I use an extension method to serialize objects somehow like this:

MyObject obj = new MyObject();
obj.ToXmlFile("some directory\\some file.xml");

The method "ToXmlFile" is defined elsewhere far apart from MyObject to
work for all objects:

public static void ToXmlFile<T>(this T obj, string path)
{
//do the right thing
}
Hmm. This sounds far inferior to having a class whose job it is to
serialize. Something like, I don't know, XmlSerializer. Static methods are
quite inflexible, and serialization is one of those things where relying
on the One True Approach for everything will probably get you in trouble.

Even if you don't like XmlSerializer, the basic approach of that is sound:
use an object to serialize. Creating an object is more flexible than
calling a static method (as there are more ways of doing the former than
doing the latter). That object can also reuse any run-time structures that
need to be built for serializing a given type. Doing such caching for a
static method will just involve creating similar objects in the
background, at increased bookkeeping overhead.

Aside from that, using an extension method for this just seems wrong.
Extension methods are supposed to provide additional functionality for
specific types. Defining one that works on any T is like extending Object
itself, and that's pretty far-reaching. It makes it harder to reason about
classes and objects in terms of responsibilities: there are no classes or
objects responsible for serialization in your model, it's actually this
one method that's doing the work -- even thought it *appears* as if
individual objects are responsible.
>And of course there is another method being a "classic" static method
that reads the XML file and deserializes its contents:

public static T FromXmlFile<T>(string path)
{
//do the right thing the other way round
}

That method is called:

MyObject obj =
MyXmlSerializerClass.FromXmlFile<MyObject>("somew here");

Now my question is: Can you think of a possibility to define
"FromXmlFile" in some way that allows me to call it more convenient?
i.e.:

MyObject obj = MyObject.FromXmlFile("somewhere");

A solution that does also work for 3rd party objects whose code I can't
manipulate? i.e.:

TheirObject obj = TheirObject.FromXmlFile("somewhere");

Something one might call "static extension method"?

C# just doesn't support that, and there's really nothing to be gained from
it. Extension methods are a double-edged sword as it is: they're bad for
readability as it's not immediately clear where a method is coming from,
and they're good for readability as they preserve traditional O-O
semantics in absence of developer clairvoyance.

Static methods on classes are not traditional O-O semantics, though, and
the minor readability gain they offer in a scenario like this doesn't
weigh against the drawbacks extension methods have.

--
J.

Jun 27 '08 #3
Jeroen Mostert wrote:
Steffen Bobek wrote:
>Let me put my approach straight. I think every developer's goal is to
write easily readable and understandable code. And to me this is
(amongst others) excellently done by extension methods, because you
write significantly less code and separate your code by functionality
at the same time (in my case XML serialization is coded in one place
only).
Extension methods aren't all roses and sunshine, though. They also have
drawbacks:

- The former assumption that a call of the form A.B() involves a method
.B() defined either in class A or one of its base classes no longer
holds. The definition of .B() could be anywhere in the set of referenced
classes. UI support is critical.

- To be able to use .B(), you must be aware that it's an extension
method, so you can reference the proper assembly and use the proper
namespace. It's not longer clear what A offers just by reading source code.

- In the same vein, generating useful documentation becomes harder:
either the extension methods are integrated with A (which requires that
all known assemblies offering extensions should have their documentation
generated in one big set) or they're left in the documentation for the
extension class (which makes .B() harder to look up for clients of A).

- The author of A will be unaware of extension methods. If they make a
breaking change, the extension methods may stop working. Of course, the
same would happen to code in a static method, but the nature of the
extension method makes it unclear who is responsible for .B().
In my opinion extensions methods are like operator overloads.

Very valuable in the few cases where it makes sense.

Should not be used in most cases.

Arne
Jun 27 '08 #4
Hi!
In my opinion extensions methods are like operator overloads.
Very valuable in the few cases where it makes sense.
Should not be used in most cases.
I completely agree. And although some voice that writing less code is not
that important, I feel that it leads to more readable and elegant code. And
when extending standard types from the BCL (such as XmlNode etc.), it's
really not that hard to determine, whether a method came from the actual
type or an extension.

Use where appropriate, not just because it's possible.

--
With regards
Anders Borum / SphereWorks
Microsoft Certified Professional (.NET MCP)

Jun 27 '08 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Jim Newton | last post by:
hi all, i'm relatively new to python. I find it a pretty interesting language but also somewhat limiting compared to lisp. I notice that the language does provide a few lispy type nicities, but...
10
by: steve bull | last post by:
I have a class SwatchPanel which takes Swatch as a parameter type. How can I call a static function within the Swatch class? For example the code below fails on TSwatch.Exists. How can I get the...
9
by: Steve Richter | last post by:
in a generic class, can I code the class so that I can call a static method of the generic class T? In the ConvertFrom method of the generic TypeConvert class I want to write, I have a call to...
14
by: d-42 | last post by:
Hi, Is there any way to make this method inheritable and have it behave appropriately on inherited classes? Using generics? Extension methods? Something else? class baseClass { public...
3
by: Filip Zawada | last post by:
Hi, I've encountered a rather interesting language problem. Suppose I've got following types: //class providing usefull static methods public class GoodBase<T> { public static void Met(){};...
4
by: Rene | last post by:
Hi, I was wondering if anyone could tell me why extension methods must be declared on static classes. I mean, why not allowing them to be declared as static methods in regular instance classes?...
5
by: Bill McCormick | last post by:
Hi C# programmers, I'd like to be able to call a static function or property and have it return a generic list. The compiler indicates that "static types cannot be used as generic arguments", so...
2
by: Andrus | last post by:
Winforms UI assembly has static FormManager.FormCreator method which creates forms taking entity as parameter. I need to pass this method to business objects in business assembly so that business...
0
by: SimonDotException | last post by:
I've written an abstract base type which uses generics to provide XML serialization and deserialization methods for use by its derived types, but I'm seemingly unable to write it in a way which...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.