473,378 Members | 1,607 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,378 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 3333
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...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.