Why I have to write the namespace to access to this extension method?

I have a project that has class to implement extension methods for some type. For example I have this class for ObservableCollection:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Collections.ObjectModel;


namespace MyProject.Collections.Utils
{
    public static class ObservableCollection
    {
        public static void RemoveAll<T>(this ObservableCollection<T> collection, Func<T, bool> condition)
        {
            for (int i = collection.Count - 1; i >= 0; i--)
            {
                if (condition(collection[i]))
                {
                    collection.RemoveAt(i);
                }
            }
        }//RemoveAll
    }
}

With this class, in my main project I can use this library with the using:

using MyProject.Collections.Utils

And when I want to use the extension methods I can do:

ObservableCollection<MyType> myOC = new ObservableCollection<MyType>();
myOC.RemoveAll(x=>x.MyProperty == "123");

So I have access to my extension method.

However, I have another class for Decimal, is this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace MyProject.Decimal.Utils
{
    public static class Decimal
    {
        public static decimal? Parse(this string paramString)
        {
            try
            {
                myCode
            }
            catch
            {
                throw;
            }
        }//Parse
    }
}

But in this case, although in my main prject I import the class:

using MyProject.Decimal.Utils;

If I do this:

decimal? myDecimalParsed= Decimal.Utils.Decimal.Parse("123");

Why in this case I can't do this?:

decimal? myDecimalParsed= decimal.Parse("123");

thank so much.

Jon Skeet
people
quotationmark

Two problems:

  • You can't use extension methods as if they were static methods of the extended type
  • System.Decimal already has a Parse method, and the compiler always looks for "real" methods before extension methods.

In fact, you can write

decimal? miTiempoEstimadoParseado = decimal.Parse("123");

... but that will just call the normal method and then convert the decimal to decimal? implicitly in the normal way.

Note that you're not really using your method as an extension method at the moment anyway - to do so you'd write something like:

decimal? miTiempoEstimadoParseado = "123".Parse();

... but personally I'd view that as pretty ugly, partly as the method name doesn't indicate the target type at all, and partly because by convention Parse methods throw an exception instead of returning a null value on failure. You probably want to come up with a different name.

people

See more on this question at Stackoverflow