What does IFormatProvider do?

Viewed 145099

I was playing around with the Datetime.ParseExact method, and it wants an IFormatProvider...

It works inputting null, but what exactly does it do?

9 Answers

In adition to Ian Boyd's answer:

Also CultureInfo implements this interface and can be used in your case. So you could parse a French date string for example; you could use

var ci = new CultureInfo("fr-FR");
DateTime dt = DateTime.ParseExact(yourDateInputString, yourFormatString, ci);

IFormatProvider provides culture info to the method in question. DateTimeFormatInfo implements IFormatProvider, and allows you to specify the format you want your date/time to be displayed in. Examples can be found on the relevant MSDN pages.

The DateTimeFormatInfo class implements this interface, so it allows you to control the formatting of your DateTime strings.

The question asks about IFormatProvider and DateTime, but you can use IFormatProvider also in other contexts of .NET, such as for string.Format.

Then you pass in the IFormatProvider instance and you can by implementing IFormatProvider specify how the string is formatted for an object. So the usage of IFormatProvider and a related ICustomFormatter interface is more broad in .NET than just for dates.

E.g. consider this implementation :

using System;

namespace ConsoleApp
{
    class EmployeeProductivityFormatProvider : IFormatProvider, ICustomFormatter
    {
        public string Format(string format, object arg, IFormatProvider formatProvider)
        {
            int rating = (int)arg;

            if (rating == 0)
            {
                return $"{rating} (new employee)";
            }

            if (rating > 0)
            {
                return $"{rating} (good employee)";
            }

            return $"{rating} (bad employee)";
        }

        public object GetFormat(Type formatType)
        {
            if (formatType == typeof(ICustomFormatter))
            {
                return this;
            }

            return null;
        }
    }
}

Now we can get a string representation of an employee by specifying an int value like this:

    string prod = string.Format(new EmployeeProductivityFormatProvider(),
                                "Productivity rating: {0}",
                                employee.ProductivityRating);

When it comes to DateTime, there are a lot of already created IFormatProvider implementation to choose from. This is a very flexible way of representating objects to strings and specifying their format in .NET and a very general concept.

Related