Search code examples
c#datetimestaticnamespacesextension-methods

How can I use an extension method without importing the whole namespace?


I am using the Google.Api.CommonProtos NuGet package with my C# service, and want to use the Google.Type.Date type alongside the System.DateTime type. I also want to use the included extension methods to convert back and forth between System.DateTime and Google.Type.Date.

The problem is that when I import the extension method .ToDate(), it brings in the entire Google.Type namespace which causes DateTime to be ambiguous between System.DateTime and Google.Type.DateTime. This code does not build:

using System;
using Google.Type;

namespace Example
{
    public class ExampleClass
    {
        public Google.Type.Date TomorrowDate(DateTime date) => date.AddDays(1).ToDate();
    }
}
// Error    CS0104  'DateTime' is an ambiguous reference between 'Google.Type.DateTime' and 'System.DateTime'

I am fine with being verbose when referencing a Google.Type.DateTime, but I don't want to start rewriting all uses of DateTime in our app to say System.DateTime. How can I achieve this? Effectively, how can I use extension methods defined in a specific class without importing (using in C#) the entire namespace where the extension methods are declared?


Solution

  • C# can statically use classes to permit access to statically defined methods; extension methods are static. In the above example, the .ToDate() extension method is defined in the Google.Type.DateExtensions class (in the Google.Type namespace), so it's possible to statically use that class only to get access to its extension methods, rather than importing the entire Google.Type namespace.

    This code works:

    using System;
    using static Google.Type.DateExtensions;
    
    namespace Example
    {
        public class ExampleClass
        {
            public Google.Type.Date TomorrowDate(DateTime date) => date.AddDays(1).ToDate();
        }
    }
    

    Original answer: https://github.com/googleapis/gax-dotnet/issues/418