extension-methods

Why can't I implicitly cast a Delegate with Extension methods?

I'm trying to figure out a way to automatically cast something to an Action or Func and the best I can come up with is something like this: [TestFixture] public class ExecutionTest { public void BadMethod() { throw new Exception("Something bad happened"); } [Test] public void TestBadMethod() { //...

Using Extensions: Weighing The Pros vs Cons

Recently I asked a question about how to clean up what I considered ugly code. One recommendation was to create an Extension Method that would perform the desired function and return back what I wanted. My first thought was 'Great! How cool are Extensions...' but after a little more thinking I am starting to have second thoughts about ...

C#, Linq2SQL: Creating a predicate to find elements within a number of ranges

Lets say I have something called Stuff in my database, with a property called Id. From the user I get a sequence of selected Range objects (or rather I create them from their input) with the Ids they want. A stripped down version of that struct looks like this: public struct Range<T> : IEquatable<Range<T>>, IEqualityComparer<Range<T>> {...

How do I use Moq to mock an extension method?

I am writing a test that depends on the results of an extension method but I don't want a future failure of that extension method to ever break this test. Mocking that result seemed the obvious choice but Moq doesn't seem to offer a way to override a static method (a requirement for an extension method). There is a similar idea with Moq....

Is there a way I can dynamically define a Predicate body from a string containing the code?

This is probably a stupid question, but here goes. I would like to be able to dynamically construct a predicate < T > from a string parsed from a database VARCHAR column, or any string, for that matter. For example, say the column in the database contained the following string: return e.SomeStringProperty.Contains("foo"); These code...

Is it wise to use LINQ to replace loops?

Now that we have tremendous functionality thanks to LINQ, I'm wondering which syntax is preferable. For example, I found the following method (just thought it was a good example): foreach (FixtureImageServicesData image in _fixture.Images) { if (image.Filename != _selectedFixtureImage.Filename && image.IsPrimary) { image...

why is LINQ to SQL tricked by an extension method? what now?

Consider my Event class, and that i store DateTime's in the DB as UTC dates. I simply want to return a filtered range based on the current date in a particular time zone - easy right? This works fine: IQueryable<Event> test1 = this.GetSortedEvents().Where(e => e.FinishDateTime.Date >= DateTime.UtcNow.Date); This also works fine: IQ...

When do Extension Methods break?

We are currently discussing whether Extension methods in .NET are bad or not. Or under what circumstances Extension methods can introduce hard to find bugs or in any other way behave unexpectedly. We came up with: Writing an extension method for types that are not under your control (e.g. extending DirectoryInfo with GetTotalSize(), e...

C#: Extension properties

I am pretty sure it doesn't, but... Do extention properties exist? Will they exist? Anyone heard anything? I would love it if they did... I mean, are they not just technically a get and a set method? Now for example I would love it if I could add an extention property to DateTimeFormatInfo called ShortDateLongTimeFormat which returned S...

Select the next N elements of an IEnumerable<T>

Say you've got some IEnumerable called S of length N. I would like to select all continuous subsequences of length n <= N from S. If S were, say, a string, this'd be pretty easy. There are (S.Length - n + 1) subsequences of length n. For example, "abcdefg" is length (7), so that means it has (5) substrings of length (3): "abc", "bcd", "...

When does a library deserve the be called "Linq-something" or "something-Linq"?

I just looked at one of those libraries that is of the naming schema "something-Linq" expecting to gain some more knowledge on how to construct expression trees in an elegant way - and was disappointed. Because all I could find were methods that extended IEnumerable - of course with "normal" C# code. Now I have this question: Do non-exp...

Handling null references when using eg Linq-To-Xml

Is there a better/shorter way to handle (lots of) null references, for example when I'm using LinqToXML. I wrote this extention for XElement that handles it quite nicely, but maybe there is another way? And what about the function name? "And" isn't really descriptive. public static class XmlExtentions { public static T And<T>(th...

C# Extension Method - String Split that also accepts an Escape Character

I'd like to write an extension method for the .NET String class. I'd like it to be a special varation on the Split method - one that takes an escape character to prevent splitting the string when a escape character is used before the separator. What's the best way to write this? I'm curious about the best non-regex way to approach it....

How to deal with a flaw in System.Data.DataTableExtensions.CopyToDataTable()

Hey guys, so I've come across something which is perhaps a flaw in the Extension method .CopyToDataTable. This method is used by Importing (in VB.NET) System.Data.DataTableExtensions and then calling the method against an IEnumerable. You would do this if you want to filter a Datatable using LINQ, and then restore the DataTable at the e...

Compiler error referencing custom C# extension method

Hello, I am trying for the first time to create an extension method and i am having some trouble... maybe you guys can help out :) public static class Extentions { public static int myMethod(this MyClass c) { return 1; } } then when i do "MyClass.myMethod" i get q compiler error saying tha...

C# Extension Methods Architecture Question

I recently asked this question: http://stackoverflow.com/questions/638463 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 t...

Faster way to do a List<T>.Contains()

I am trying to do what I think is a "de-intersect" (I'm not sure what the proper name is, but that's what Tim Sweeney of EpicGames called it in the old UnrealEd) // foo and bar have some identical elements (given a case-insensitive match) List‹string› foo = GetFoo(); List‹string› bar = GetBar(); // remove non matches foo = foo.Where(x ...

String.IsNullOrBlank Extension Method

I continuously check string fields to check if they are null or blank. if(myString == null || myString.Trim().Length == 0) { throw new ArgumentException("Blank strings cannot be handled."); } To save myself a bit of typing is it possible to create an extension method for the String class that would have the same effect? I understa...

With the advent of extension methods, are abstract classes less attractive?

One interesting aspect of extension methods in .NET is the fact that you can apply them to interfaces. For me, it seems nice that I can define functionality near the interface without defining an abstract class that clutters the assembly. I know that abstract classes are not obsolete or anything, but how do you feel about utilizing this...

Accessing HtmlHelper methods within HtmlHelper extension method - ASP.NET MVC RC2

I am trying to build an HtmlHelper extension in ASP.NET MVC RC2. This code worked fine in Preview 5, but does not work anymore in RC2 and I am trying to understand why. Here is the code: public static string EmptyDropDownList(this HtmlHelper htmlHelper, string name, object htmlAttributes) { return htmlHelper.DropDownList(name, new S...