The example provided in Microsoft's documentation for Clipboard.ContainsImage()
includes the following:
System.Drawing.Image returnImage = null;
if (Clipboard.ContainsImage())
{
returnImage = Clipboard.GetImage();
....
}
The superficial / nominal behavior of this method is to first check if the clipboard contains an image, and if so acquire that image for use. Return null
otherwise.
However, isn't it possible that in-between the call to ContainsImage()
and the call to GetImage()
another application has changed the contents of the clipboard? There might be no image data after all.
When the clipboard does not contain an image, GetImage()
is documented to return null
. Fine, but then what is the point of calling ContainsImage()
in the first place, if when you call GetImage()
it is mandatory to inspect the result anyway?
This doesn't just apply to this example - what ever would be the use of calling ContainsImage()
if you actually need the clipboard contents?
Maybe ...
It is more performant than calling GetImage()
, therefore its worth doing even though in a small % of cases GetImage()
will fail?
Some magic locking is going on which solves this problem automatically (highly doubtful)?
A case where ContainsImage()
might be useful would be if you do not need to acquire the clipboard contents, just to see if they are imagery.
Imagine that you have a button and you want to Enable whenever there is an Image in Clipboard and disable it otherwise.
calling ContainsImage()
regularly does not have a big cost as it is a flag that is set just once when an Image is set to Clipboard). but getting the Image itself every time just to make sure that there is an image in the Clipboard is costly.
A different Example:
Imagine that you have byte[]
that can contain Video, Image or Audio.
public enum MediaType
{
Audio,
Video,
Image,
None
}
class MyData
{
private byte mydata = null;
private MediaType type = MediaType.None;
public void SetData(byte[] data)
{
mydata = data;
if(ImageValidation()) // a method that validates data is a valid image
type = MediaType.Image;
else if(VideoValidation())
type = MediaType.Video;
else if(AutioValidation())
type = MediaType.Audio;
else
type = MediaType.None;
}
//I'm not going to create all get functions but just for one type
public bool ContainsImage() //costless
{
return type == MediaType.Image;
}
public Image GetImage() //costly if there is an image
{
if(type == MediaType.Image)
using (var ms = new MemoryStream(mydata))
{
return Image.FromStream(ms);
}
else
return null;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With