C# Feature Idea: Static Extension Methods
Extension methods are really useful - no two ways about it. Being able to add my own methods to an existing class makes for some very readable code.
Extension methods, however, are currently only instance methods. There's no syntax for defining a static extension method on a type rather than an instance. For example, suppose I wanted to define a static method called Yesterday() on the DateTime class, so I could do this:
var d = DateTime.Yesterday();
It's a trivial example, I know, but you get the idea. Another example might be to create a static method to create an instance of a type - like the TryParse() method we get on a few inbuilt classes.
I'm thinking that the syntax could use generics and look something like this:
public static DateTime Yesterday<this DateTime>()
{
return DateTime.Today.AddDays(-1);
}
So I've used the "this" keyword (in much the same way that normal extension methods do) except I've used it in the generic type argument. DateTime now has a static method called Yesterday.
Obviously static extension methods would only call static members (unless they take a parameter).
Perhaps C# 4.0 could introduce a feature like this. Would you use it?
# Trackback from Jason Haley on 7/02/2008 3:26 AM
# Trackback from Reflective Perspective - Chris Alcock » The Morning Brew #27 on 7/02/2008 6:03 PM
# Trackback from Simple syntax for getting a member of a type in extension method (C#) | The Largest Forum Archive on 24/07/2010 9:35 PM
Comments
# Sasha Goldshtein
7/02/2008 7:01 AM
I don't feel a strong connection between this kind of feature and generics, so I find it difficult to second your syntax.
By the way, what's so wrong with just doing:
static class DateTimeEx {
public static DateTime Yesterday() { ... }
}
It looks almost as good as the original, and if you have a good coding convention in place it might even work.
Alternatively, you could go for:
namespace Extensions {
static class DateTime {
public static System.DateTime Yesterday() {...}
}
}
And then you'd have:
DateTime yesterday = Extensions.DateTime.Yesterday();
Not so bad either.
# mabster
7/02/2008 8:51 AM
Yeah, the link to generics is tenuous at best, but it's a language construct we already have to tie a method to a type (rather than passing in a parameter of type Type), so it seemed like a logical way of declaring an extension method on a type rather than an instance.
Certainly both of your examples work, but then old-fashioned static methods also work in place of extension methods, but I think we all agree that the latter makes for more readable code.
I think if I was reading code that said:
var d = DateTime.Yesterday;
... then I'd instantly recognize that "d" is a DateTime. If I saw this:
var d = DateTimeEx.Yesterday;
... then it's a little less clear.
# Skup
7/02/2008 7:24 PM
Hi,
the use of generics on a method is usualy not used to tell on which object the method is, but to give a type to arguments... so i'm not sure it's the better option.
I was thinking to enable static class inheritance...
public static class DateTimeEx : DateTime
{
...
}
since the class is static it cannot extend the instance, but propose new static methods for it..
the caveats is that we would like to use the DateTime, and it is not natural to have methods declared on a derived type appearing on a base type...
Should continue to think about it..
# david alpert
8/02/2008 7:42 PM
I would definitely use the feature; i just wrote some custom Constraints for NUnit 2.4.6 and wanted to add some static properties to the Has SyntaxHelper so that i could write:
Assert.That(p, Has.MyCustomConstraint);
This is very readable syntax; the static properties on the Has class return instances of Constraint classes that Assert.Test then applies to p - very cool and DSL-like.
I agree, however, that the use of Generics syntax muddies the issue a bit.
How about simply adding the static keyword into the extension method declaration? And while we're at it, enhancing the extension method syntax to support extension properties like so:
public static class HasExtensions {
public static MyCustomConstraint MyCustomConstraint(static this Has) {
get {return new MyCustomConstraint(); }
}
}
# Brett
13/02/2008 4:19 PM
How about
public static DateTime Yesterday(this DateTime) { }
or
public static DateTime Yesterday(static DateTime d) { }
(similar to above but no need for this keyword)
# mabster
14/02/2008 2:40 PM
Actually, the second one sounds good. The 'static' keyword in place of the 'this' keyword. It wouldn't actually need the "d" though, since there is no "d" to act on:
public static DateTime Yesterday(static DateTime) { }
# David Nelson
20/02/2008 7:29 AM
The difference between instance extension methods and the static extension methods you propose is that instance extension methods reorder the code resulting in making it more readable, whereas your static extension methods merely replace one type with another, without making the code more readable. I think all you are doing here is adding language complexity without adding value.
# mabster
20/02/2008 7:39 AM
Hi David,
I'm not sure I'm "replacing one type with another" at all. My DateTime.Yesterday() example doesn't introduce any new types - it just adds a static method to DateTime.
David Alpert's example of an Assert.That() overload above is another good one.
# david alpert
20/02/2008 7:41 AM
back to my NUnit example, static extension methods would allow me to add my custom properties to an _existing_ static helper class.
this improves readability, no?
Wouldn't you rather see
DateTime y = DateTime.Yesterday
than
DateTime y = DateTimeEx.Yesterday
or
DateTime y = Extensions.DateTime.Yesterday()
Isn't the first one more clear, more readable, and, provided that the static extension code is in a findable location, more maintainable?
# David Nelson
22/02/2008 9:55 AM
Matt and David Alpert,
My point was that all you gain from this is the ability to go from David's second example to his first, i.e. "replacing" DateTimeEx with DateTime. That seems to me to be an extraordinarily small gain in exchange for additional language complexity and reduced maintainability.
# mabster
22/02/2008 10:48 AM
Yeah, I won't deny that it's a small gain.
The readability benefit is clear though. Imagine something like this:
Assert.That(x == y).And.That(a != b).AndEx.IsEmpty(myString);
Because I had to define my own "IsEmpty" static method, I had to create an "AndEx" class to contain it. That harms readability IMHO.
It's a trivial thing but it'd be cool to have.
# David Nelson
26/02/2008 1:11 AM
I agree there is a small readability gain. I just don't think it meets the "minus 100 points" test. This is of course a subjective assessment. But in my opinion, extension methods as they exist today are already like handing a loaded gun to a toddler; I fear what they will do the future maintainability of the language. I am not normally one to worry about what how a powerful feature might be abused, but in this case I am afraid that the lure of "readability" will cause many, many people to go too far with this feature. I am also concerned about the enormous potential for breaking changes (several people from the various .NET teams have blogged about this, including Eric Lippert). Instance extension methods introduce a new variation of the fragile base class problem, and static extension methods would just compound the problem.
# Vitaly Orlov
4/03/2008 6:54 AM
I think mabster asked for something I have been wishing from the birth of C#.
You might think it's a small gain but I think it's not. Because most stuff is dangerous if you abuse them. I mean look at var feature of C# 3.0. If it's abused, it would be the most fearful nightmare for C# IMO.
So stuff like this really helps with the workflow, and clarity, and just like instance extension methods are extremely easy to understand. Just show the syntax, and done! You already learnt it.
Is there a way we can pass this onto C# team? I already heard they are planning to add instance extension properties.
# Andrew Tobin
4/03/2008 10:31 AM
I always find it a tad bizarre when someone mentions that a function in C# would be a nightmare if abused.
Anything in a programming language is a nightmare if it's abused.
Heck, commenting is a nightmare if it's abused (for the next person maintaining).
I don't think, when speaking about programming languages, that the fact it _could_ be abused is a valid reasoning for not having a piece of functionality.
User applications, certainly, but we need to place some trust in the developers hands that they'll do the best they can to be effective, efficient, and work to best practices.
On the downside, you get viruses, worms, keyloggers, etc, etc.
On the plus side, for those of us who do the right thing, we get a bit more power that makes us efficient and allows us to write better software.
It's okay if you want to write something managed that saves me from having to worry about the background stuff (memory management, etc), but there's no need to protect me from misusing something, because I'll learn a better way as soon as I can.
# David Nelson
5/03/2008 2:16 AM
@Andrew,
As I said, "I am not normally one to worry about what how a powerful feature might be abused." The reason I don't usually worry about it is because the potential gain far outweighs the risk of some developers abusing the feature. However, in this case, I believe that the potential gain is so small that it does not outweigh that risk, or the other negative impacts that adding a feature to a language has.
# Vitaly Orlov
5/03/2008 7:34 AM
But isn't it the same thing with instance extension methods?
# David Nelson
5/03/2008 8:21 AM
@Vitaly,
No, its not the same. Instance extension methods physically rearrange the code to be more in line with what we expect to see when looking at object-oriented code. This results in a substantial increase in readability. But static extension methods do not rearrange the code; they merely replace one type name with another type name within an expression. So the readability gain is extremely small, and as I said, not worth it IMHO.
# Vitaly Orlov
6/03/2008 4:02 AM
But instance extension methods don't cover all bases in what we want to see.
For instance, IMO it's more readable to use:
Vector3.Dot(v1, v2)
than
v1.Dot(v2)
I think it's these kind of things that static extension methods would shine.
# David
7/03/2008 1:22 AM
@Vitaly,
You can accomplish that same thing with:
Vector3Math.Dot(v1, v2)
Maybe its not quite as readable, but its close. This is what I meant when I said that static extension methods only result in a very small readability gain, which is not (IMHO) worth implementing a language feature for.
# Vitaly Orlov
7/03/2008 5:25 AM
I see what you mean. But we could do this if we didn't have instance extension methods, right?
Scramble(myString)
instead of
myString.Scramble()
Aren't these the same too? Or is it because instance extension methods avoid referencing arguments, like:
Scramble(ref myString)
# David Nelson
7/03/2008 6:44 AM
Yes, technically instance extension methods do not allow us to do anything we couldn't do before (unless you are relying on duck typing like LINQ is, in which case they are necessary). But the point is that they rearrange the code to increase readability by turning functional statements like Scramble(myString) into object-oriented statements like myString.Scramble(). Static extension methods don't rearrange the code; ALL they do is replace one type name (Vector3Math) with another type name (Vector3) within an otherwise identical expression.
# Vitaly Orlov
7/03/2008 10:40 AM
That makes sense. When you said they are necessary for duck typing, did you mean using var?
If so, I thought they were separate things. Can you please give me an example?
# David Nelson
8/03/2008 3:20 AM
No, I don't mean the use of var. Implicitly typed variables are not a form of duck typing, they are just a way to refer to anonymous types.
I have written a post about LINQ and duck typing on my blog at commongenius.com/.../linq-and-duck-typing.aspx.
# Vitaly Orlov
8/03/2008 6:18 AM
Thanks. I got it now.
# Jeff
4/12/2008 7:43 AM
I can think of one problem with using conventions proposed in examples like the following in that it doesn't lend itself to good practices with regard to reflection, refactoring, and other types of static analysis.
Vector3Math.Dot(v1, v2)
DateTime y = DateTimeEx.Yesterday
DateTime y = Extensions.DateTime.Yesterday()
The reason is that by using DateTimeEx by convention bares no actual code connectino between DateTimeEx and DateTime.
A little off topic, but an interesting aspect of static extension methods would be that this would may provide for a way of extending Factory methods to provide more customized construction logic. Sort of the same thing that makes the new type initialization syntax so handy { P1 = "1", P2 = 2}.
# Szymon Matyjaszek
7/01/2009 3:40 AM
I totally agree about static extension methods.
In web applications an ordinary practice is to separate data logic and web-related logic (stuff that relies on HttpContext in any way). Since C#3.0 there's a comfy way to do this without defining hundreds of new classes. Assuming it's a data-related application and you have your entity logic in SomeProject.SomeNamespace, you just put some extension methods in SomeProject.SomeNamespace.Web (preferably in some other assembly file) and that's it. You do to your classes exactly the same thing as System.Linq does to IEnumerable for example. Still, due to the lack of static extension methods, whenever you need a static web-aware method for your base logic class, you have to put together a "Helper" or "Manager" class which gets it done. Then instead of doing SomeEntity.FromSession(...) for example, you do SomeEntityManager.GetSomeEntityFromSession(...) which is far from perfectly comfortable. Aside from that, in the end mostly you realize that you already have 50 of those helpers/managers, each defining just a couple of methods. In such scenarios, static extension methods would be a cure.
As for the syntax, I like this one:
public static DateTime Yesterday(static DateTime) { }
# Michel Heemskerk
14/01/2009 7:26 PM
Wow this blog post is a long running one, still getting new replies after eleven months!
I agree completely. When extension methods were introduced I hoped it would finally give all those static utility classes (that we all have) a place within an existing object model. But without static extension methods, you'll still have to maintain utility classes, resulting in a class library now containing BOTH extensions and utilities. Talk about adding complexity...
And it would be so simple to implement, I just don't get why they even used the "static" keyword for extensions. Would this not just be enough for the compiler to recognize them:
void Foo(this DateTime dateTime)
{
}
Then, you could make a STATIC extension like this:
static void Foo(this DateTime dateTime)
{
}
By the way, I'd like extension properties and other member types as well:
string Foo(this DateTime dateTime)
{
get;
set;
}
This could give more compiler problems, but i don't believe it's not doable. In my opinion, this is just something that Microsoft introduced without thinking it fully through.
# Mauricio
3/02/2009 12:22 PM
F# has static extension methods: codebetter.com/.../object-oriented
Sadly, they're not visible from other languages since they don't have the syntax for this...
# TT
8/02/2009 5:30 AM
I think static extension methods are just as natural and valueable as instance extension methods. I was in need of a new static method on the System.Drawing.Image class that would allow me to load the image from a byte array like this, Image.FromByteArray just as you have .FromFile and .FromStream.
something like ImageEx.FromByteArray would be pretty useless in my opinion as the whole point with the extension methods is to make the methods discoverable.
# Daniel Smith
6/03/2009 9:13 AM
Here's an example of how I'd implement extensions:
public extends DateTime
{
// Extension property
public DateTime Tomorrow
{
get { return this.AddDays(1); }
}
// Extension method
public static DateTime SetTime(this DateTime d, int hour, int min, int sec)
{
return new DateTime(d.Year, d.Month, d.Day, hour, min, sec);
}
// Static extension method
public static int DaysBetween(DateTime startDate, DateTime endDate)
{
return endDate.Subtract(startDate).Days;
}
}
Notes:
* The "this" keyword represents the instance of the object the extension method/property is attached to.
Benefits:
* There is no need for a dummy "this" parameter on the extension methods as with the old syntax.
* Extensibility - it would be easy to see how other extensions could be added e.g. indexers, etc.
* Keeps all your extensions for a class together.
* Clean, concise, familiar syntax without any freaky tricks.
* Other than the enclosing "extends X" everything inside the braces is normal code.
* The same rules that classes use for the "this" keyword apply to the new "extends X" construct i.e. the "this" keyword can only be used in the non-static extension methods.
# Damien McGivern
25/03/2009 11:00 AM
Hi Matt, I like this feature idea but I disagree with the syntax you've gone with.
'this' refers to an instance, see http://msdn.microsoft.com/en-us/library/x53a06bb(vs.71).aspx, and as we're dealing with static methods I don't think 'this' should be used but I do agree that the syntax should use generics as there is no instance to pass in like current extension methods.
something like:
public static DateTime Yesterday<static DateTime>()
{
return DateTime.Today.AddDays(-1);
}
or perhaps as we're adding to a class rather than an instance we should require that the static extension methods are within a static class that extends the class type.
public static class DateTimeExt : DateTime
{
public static DateTime Yesterday()
{
return DateTime.Today.AddDays(-1);
}
}
This would allow you to use the method via the new class or the extended class.
DateTime.Yesterday() or DateTimeExt.Yesterday()
Wrapping in a class makes organising/grouping static extension methods easier
# DanielM
14/04/2009 11:01 PM
I've been frustrated about the lack of static extension methods several times, especially when doing framework development that other people rely on.
The problem is mostly that Microsoft uses a To/From pattern in many cases and users rely on this pattern.
Ex. _color.ToArgb() and Color.FromArgb(...)
If ex. I wanted to convert an Image instance to a byte[] I would just create a ToBytes() extension method, that part would be easy today.
I would then like to create the counterpart, Image.FromBytes(...) - but there is no way I can do this today.
This is a problem because that is where users would expect to find this method, especially when this is where they will find methods such as Image.FromStream and Image.FromFile.
I could create a _byteArray.ToImage(), but that would be a horrible coupling.
There are lots of other places in the .NET framework where this To/From pattern is evident.
It would take considerable time to make users adjust to a [Class]Ex pattern for such methods and it would only work in a controlled environment (eg. a small office-team).
I hope the C# team reads your blog :)
# Michal
10/06/2009 4:17 AM
I ditto need for static extension methods. While porting/dual building full framework app to a compact framework I need to re-implement many missing methods, such as Math.Log(val,base). Can't keep my code from having #if WindowCE stuff.
BTW, MS really messed up CF just to save few bytes here or there. :-(( Very frustrating experience!
# PaulB
18/07/2009 3:34 AM
I just ran into a case where I really wanted this. I wanted to extend the File object with a few extra operations.
It's ugly to have to "just know" when to use File and when to use FileEx. They're all closely associated operations, and putting new static methods on File seems exactly the right thing to do.
I think it enhances not only readability, but usability and maintenance.
Never mind the simple matter of consistency. It seems perfectly consistent to be able to extend static classes in exactly the same way you do instance classes. I also support the same syntax, simply substituting "static" for "this", as a way of continuing this consistency.
Frankly, I was suprised I couldn't do this when I tried. It seems like a no-brainer to add, given we already have extension methods for instance classes.
# Jim
10/08/2009 8:48 AM
I ran across this post while looking for a way to do static extensions. Needless to say, I'd use them if they were available. Truthfully, the introduction of extension methods was so unexpectedly useful to me that I feel a little ungrateful wanting more, but extension properties and static extensions methods seem like the next logical steps.
# Matt
3/09/2009 12:53 AM
I've also been pining after static extension methods for some time now. They would be especially useful for immutable types (I'm guessing this is why they were implemented in F#).
Regarding the syntax, my first thought was simply replacing the 'this' keyword of a standard extension method with 'static' eg:
static public string Something(static string s)
However thinking about that more, that could be extremely confusing for people coming to C# from other languages, where putting static in front of a method paramter means something completely different (I've seen this in HLSL but I'm sure it's in other languages).
So I actually agree with Daniel Smiths idea, something like this:
public extension class StringExtensions
{
// Instance extension method
public void DoSomething()
{
// We automatically have a 'this' instance...
}
// Static extension method...
static public string SomethingElse()
{
// We have no 'this'...
}
}
This kind of syntax would also be scalable for future additions such as extension properties or indexers. I think extension constructors would be a nice addition too as long as they forced a call to one of the base constructors.
# Danny Miller
23/12/2009 7:27 AM
I'd LOVE to have static extension methods. I need the fact that the new static library method I wrote to TryParse an enum (without using try/catch) to be noticed by other developers when they begin to type out Enum.Parse(). Without an extension method, nobody realizes it is there to be used.
# Siegfried Glaser
29/12/2009 12:22 AM
It would be great to have static extension methods.
Danny Miller hits the nail right on the head. A method that isn´t noticed is useless ballast.
I think a syntax like:
public static ReturnType MethodName(static ExtendedType e) { }
would do the job nicely. As Matt pointed out it might be confusing for people coming from other languages, but they will have to get aquainted with C# anyhow.
# ATC
14/01/2010 2:02 PM
@David Nelson:
With all due respect, sir, I think you're wrong. Your argument against static extension methods could also be applied to extending instance members! :) ("Just replacing one name with another," ... "[...]adding complexity...", etc) After all, it DOES just replace one name for another; it makes the code more fluid, readable, and accessible; especially for those who digest third party libraries/frameworks.
I'm working on a multi-platform game engine and a .NET extension framework right now. I'm VERY troubled by the lack of static extension methods and even the lack of the ability to extend static classes. :( It's gone so far in one case that I totally wrapped a standard static .NET class and "aliased it away". It appears now exactly the same as the System[...] counterpart but has many new features. It's just very unfortunate I had to go to such tedious lengths (THAT is what I call abuse! haha!). Now I'm even wanting to extend System.Array with new static methods; but I just don't have the time nor patience to wrap it too.
Static classes should also be extensible, imho. If we're going to have the ability to do any sort of extensions, it should follow that we can do any reasonable extensions we want. Most of the time, people want language features because it can *help* them and make life easier (and hopefully more profitable). The "preventing abuse" argument doesn't hold any water. Programmers are either good programmers who know how to write good code/designs, or they are bad programmers who write lousy code and don't know what they're doing. NO language feature (or lack thereof) can make a good programmer bad or a bad programmer good. That is, with the exception of the language being garbage, in which case no "good" programmer will use it anyway. C# is excellent, so we don't have to worry. :)
Furthermore, what concern is it of Microsoft's, yours, mine, Bob's, Jill's, or anyone elses if someone "abuses" (by our own definition) the language and its features? Absolutely none, in all truth. People "abuse" C# features, C/C++ features, etc every single day, and it has yet to bother me a bit. If I spot some software/libraries/etc where I feel features were abused and the code is lousy then I simply won't use it; end of story. It's the same case when someone follows all the design protocols but their product stinks; I just *don't* touch it. There are plenty of lousy video games with very well written code, but we still don't buy them. All of us probably feel the same, and that won't ever change, regardless of language features. The only time a feature addition controversy holds any water is when it may break existing and important features and code. Here, it is simply not the case. So it's really no one's right to try to force other programmers to follow their conventions and ideas.
I like some of the syntax ideas for static extension methods, and I have some of my own:
// I call this "reverse static member inheritence"! :)
public static int AddOne(int value)
: System.Int32
{
// ... do something...
}
// The current instance member extension syntax must remain the same...
There could also be an attribute syntax for static extension methods:
[Extension : System.Int32] // Or maybe [System.Int32 : Extension]
public static void Test() { }
Furthermore, a mechanism is needed for extending static classes...
public static extension class ConsoleExt : System.Console
{
}
Just some ideas off the top of my head! :)
# Rafael
11/03/2010 2:16 PM
Static class inheritance. That sounds good.
public static class Bar
{
}
public static class Foo : Bar
{
public static void Go()
{
}
}
All methods of Foo are implicitly (static) extension methods of Bar.
# DerinDavis
26/03/2010 5:05 PM
Definitely we required "Static Extension Methods" feature in .NET.
My requirement is like
TimeSpan result1 = TimeSpan.FromString("000125");
and it should result "00:01:25", but if we use the TimeSpan.Parse() function, I get "125:00:00".
I need a static Extension method in TimeSpan to create a timespan object from a custom string format.
I can write another static class to do the same like "TimeSpanEx" or something, but we loss the BEAUTY of the code.
So its a nice to have feature and hope to get soon.
Thanks
# DerinDavis
26/03/2010 5:05 PM
Definitely we required "Static Extension Methods" feature in .NET.
My requirement is like
TimeSpan result1 = TimeSpan.FromString("000125");
and it should result "00:01:25", but if we use the TimeSpan.Parse() function, I get "125:00:00".
I need a static Extension method in TimeSpan to create a timespan object from a custom string format.
I can write another static class to do the same like "TimeSpanEx" or something, but we loss the BEAUTY of the code.
So its a nice to have feature and hope to get soon.
Thanks
# ElectricNinja
12/08/2010 7:31 AM
My idea is automatically the best.
public static T[] GetValues<static T>() where T : Enum
{
return (T[])Enum.GetValues(typeof(T));
}
# Baard
8/09/2010 8:43 PM
I'd use it.
Here's my use case btw;
// Create a TimeSpan from a CSS2 time format string, e.g. 2h30m.
//
// This method should really be static. So that I could write
// ms = TimeSpan.FromCssTimeFormat("2h30m");
// instead of
// TimeSpan ts = new TimeSpan()
// ms = ts..FromCssTimeFormat("2h30m");
// But this ain't implemented in C#. (... yet. See http://madprops.org/blog/static-extension-methods/)
//
public static TimeSpan FromCssTimeFormat(this TimeSpan ts, string durationString, uint defaultValue)
{
uint result = defaultValue;
try
{
if (!Regex.IsMatch(durationString, @"^\d+(h|m|s|ms)(\d+(h|m|s|ms))*$"))
throw new FormatException(@"Durations must be on the format \d+(h|m|s|ms)");
Match match = Regex.Match(durationString, @"^(?:(\d+)h)?(?:(\d+)m(?!s))?(?:(\d+)s)?(?:(\d+)ms$)?");
if (!match.Success)
throw new ArgumentException("Regex mismatch.");
int h = (int)(match.Groups[1].Value.Length > 0 ? uint.Parse(match.Groups[1].Value) : 0);
int m = (int)(match.Groups[2].Value.Length > 0 ? uint.Parse(match.Groups[2].Value) : 0);
int s = (int)(match.Groups[3].Value.Length > 0 ? uint.Parse(match.Groups[3].Value) : 0);
int ms = (int)(match.Groups[4].Value.Length > 0 ? uint.Parse(match.Groups[4].Value) : 0);
return new TimeSpan(0, h, m, s, ms);
}
catch (Exception e)
{
return TimeSpan.MinValue;
}
}
# Koistya `Navin
9/09/2010 12:58 PM
I have another idea - new property system and property extensions in C# 5.0
www.fsguy.com/.../2010-09-09_prop
# Mr. Obnoxious
28/03/2011 5:44 AM
The following is currently doable, so no need for static extensions. In fact I'm going to call up Bill Gates and ask him not to put it in .NET 5.0.
public static class Extensions
{
public static T Create<T>(this T @this)
where T : class, new()
{
return Utility<T>.Create();
}
}
public static class Utility<T>
where T : class, new()
{
private static Func<object> _Create = null;
static Utility()
{
_Create = Expression.Lambda<Func<T>>(Expression.New(typeof(T).GetConstructor(Type.EmptyTypes))).Compile();
}
public static T Create()
{
return _Create() as T;
}
}
// usage below:
var ds1 = (null as DataSet).Create(); // as oppose to DataSet.Create()
// or
DataSet ds2 = null;
ds2 = ds2.Create();
# Armen Shimoon
2/09/2011 1:03 PM
I've found a need to have static extension methods for my projects, and I'm quite sad that .NET doesn't support it natively. The best possible solution I could come up with was to reusing existing instance extension method functionality, by simply introducing one class:
public class @static<T>
{
}
Then, you can write an extension method for any particular class by this:
public static class StaticDateTimeExtensions
{
public static DateTime Yesterday(this @static<DateTime> shim)
{
return DateTime.Now.AddDays(-1d);
}
}
Then, you can access all your static extension methods by constructing a new instance of your static class:
DateTime yest = new @static<DateTime>().Yesterday();
While this is a hack, it's one with the least footprint and gives the same flexibility of extension methods, along with a syntax that is somewhat understandable. I read the last line of code as "construct a new extended static representation of DateTime". It'll have to do until I find something better or C# introduces them.
# Fanged
19/12/2011 9:30 PM
I've found a preference for static extensions for a Factory pattern in a Domain/Application multi-project solution.
The Domain doesn't need the factory, but the Application does.
Example:
Domain project contains:
public class Foo {
public long Bar { get; set; }
}
Application project should contain:
public static class Extensions {
public static Foo Factory( static Foo ) {
return new Foo { Bar = -1 );
}
}
And Usage:
Foo thing = Foo.Factory();
Doing it this way maintains seperation of concerns from Domain/Application, reduces class bloat and maintains readability.
# C# Dude
25/01/2012 10:25 PM
Absolutely, wanted. Who doesn't have code statements like this:
if((myClass != null) && (myClass.MyProperty != UNKNOWN_VAULE)) {
DoMyThing();
}
with static extension methods this could look much cleaner like this:
if(MyClass.IsOk(myClass)){
DoMyThing();
}
# xr280xr
1/03/2012 2:58 AM
There's a lot of comments so sorry if this is redundant. I would use it. I was just looking for a way to add a Trim() method to String so that I could trim strings that may be null. In the end, though, it does seem unnecessary because you can easily just define your own method in any class. It would be neat to have it in the class you want it to apply to, but not sure it's actually that useful.
# mabster
1/03/2012 4:21 AM
@xr280xr,
Don't forget that extension methods as they exist today can act on objects whose value is null. So if you made a "MyTrim" extension method on System.String, this would work fine:
string s = null;
string trimmed = s.MyTrim();
All you have to remember to do is check that the "this" parameter to your extension method is null.
# George
22/11/2012 2:26 PM
Great idea!
There were a few times I could have used that instead of wasting time figuring out how to accommodate it's absence. That's 3min * 10/year * 10 years * 10,000 programmers = 50,000 work hours.
Fortunately we are no longer coding in assembly, which was considered ideal at one point.
:)