public static Fahrenheit ToFahrenheit(this Celsius celsius) { return(new Fahrenheit(celsius.Value * 9 / 5 + 32)); }
/* * Extension methods are a powerful tool in C#, but they must * be used wisely. They're well suited to adding utility to existing * classes that you may not be able to alter directly (such as framework * classes). This can help a lot with avoiding static utility methods and * helper classes which makes the calling code feel more object-oriented and * less procedural, reducing complexity in the process. However, they shouldn't * be used in all cases. Extension methods should never be used when they would rely * on the internal state of a class they're extending (beyond public getters). * They also can make classes harder to mock. If you were to add an extension method * to, say, `IFoo`: * * public static void Bar(this IFoo foo){ * Console.Writeline(foo); * } * * Note the `this` keyword. That keyword is what marks the signature as an extension method. * Extension methods must be static, the first parameter must be an instance of the type being * extended preceded by `this`, and they must be contained within a static class. * * If, during unit testing, you create a mock object, you'll find not all * mocking frameworks will capture your extension method. * * Some of the best candidates for extension methods are to extend the capabilities of a class * that you are not responsible for testing. * * Extension methods are also used heavily by 3rd party libraries (and even * the framework itself) to provide registration methods for various features. * The `AddControllers()` method in `Startup.cs`, for example, is an extension method * on the `IServiceCollection` class. It's very common to write extension methods * to expose middleware or even just cleanly register whatever types your library needs * with the DI framework. */ public static Kelvin ToKelvin(this Celsius celsius) { return(new Kelvin(celsius.Value + (decimal)273.15)); }