Posts Tagged ‘Extension Methods’

Extension Methods stop working!?

Wednesday, August 11th, 2010

I’m working on a solution where I have several different projects. Some of these projects are class libraries (DLLs) and some projects reference others. In some of them I have a number of extension methods.

I’ve noticed something strange happening occasionally. The extension methods in one of the class libraries stop functioning as extension methods for no apparent reason. This is even if they are called from within the same class library. It is usually after I have changed something, but not anything significant, and the namespace references all appear to be correct when I check. This isn’t just intellisense either – the build fails compilation.

The simple solution to this problem that I have found (which may solve other weird compilation bugs as well) is simply to clean the solution, close Visual Studio, reopen it and build again. This has worked every time that I’ve tried it so far.

This applies to Visual Studio 2010 Professional, and possibly 2008 as well, but I can’t remember if I had that problem then.

Linq to SQL Quirks Part 3 – Extension to Get Around the Delete Problem

Tuesday, June 30th, 2009
This entry is part of a series, Linq to SQL Quirks»

My previous post about problems deleting can be partly handled with an extension method to the Linq to SQL Table(Of T) class with something like this…

         Public Sub DeleteOnSubmitOrDetach(Of T As Class)(ByVal table As System.Data.Linq.Table(Of T), ByVal o As T)
            Dim IDProperty = o.GetType.GetProperty("ID")
            If IDProperty Is Nothing Then
                Throw New System.MissingFieldException("Trying to delete object of type " & GetType(T).Name & " - does not have an ID field")
            End If
            If IDProperty.GetValue(o, New Object() {}) = 0 Then
                table.InsertOnSubmit(o)
            End If
            table.DeleteOnSubmit(o)
        End Sub

Note that you’ll need to import System.ComponentModel and System.Reflection and possibly some others, and it assumes that you have an IDENTITY ID field by that name on all of your classes that you use this with.