-
Notifications
You must be signed in to change notification settings - Fork 6
Handling missing instance methods
Many of the types in the Portable Class Library profiles have been streamlined, for example by removing redundant or ambiguous instance methods and properties. One important goal is thus to deprecate the use of these methods and properties in any code.
However, when porting a large code base, replacing these missing methods everywhere can be a real burden.
Therefore, in the Shim library, some workarounds are available to keep you from editing the legacy code base. The basis for these workarounds is the use of extension methods.
For example, the .NET method Stream.Close()
in the System.IO
namespace is considered bad practice. In PCL, although the class Stream
is available the Close()
method is therefore not available, and you are instead recommended to use Stream.Dispose()
explicitly or implicitly (i.e. via a using
clause).
Now, Shim is not concerned primarily with best practices, but with facilitating the porting of .NET legacy code to PCL. Therefore, Shim provides a workaround so that you do not need to edit Stream.Close()
invocations in your code.
In the StreamExtensions
static class in the System.IO
namespace, there is namely an extension method
public static void Close(this Stream);
In code you can of course call the method like this:
Stream strm;
...
StreamExtensions.Close(strm);
But since it is an extension method, you can also call it like this:
strm.Close();
Which evidently means that legacy code using the .NET method Stream.Close()
does not need to be changed!
Within the scope of the portable class library, the call strm.Close()
will invoke StreamExtensions.Close(strm)
.
There will also not be any name conflicts when Shim is consumed from an application or library on a platform that supports Stream.Close()
, since instance methods will always have precedence over extension methods with matching signatures, according to the C# Programming Guide.