dotnet / winforms

Windows Forms is a .NET UI framework for building Windows desktop applications.
MIT License
4.38k stars 971 forks source link

Add GetData<T> Method to Clipboard #11350

Open lonitra opened 5 months ago

lonitra commented 5 months ago

Currently when grabbing items off the clipboard via Clipboard.GetData we give back type object. It would be good to add typed methods to allow users to express that they are expecting a specific type from the clipboard. This allows us to prevent giving users objects that they do not intend to receive. This will also allow us to avoid fallback to BinaryFormatter when it is not necessary since we would've checked if the requested type matches the root record and avoid the fallback if there is no match.

Note that there are some slightly more specific Clipboard.GetX methods such as GetImage() and GetAudioStream() which internally calls GetData. We would want to update these to call the new GetData<T> as well.

A follow up to this would be to add analyzers that notify users usings the old pattern (SomeType)Clipboard.GetData(); to use GetData<T>() instead

elachlan commented 5 months ago

This is great! Will you also have similar API for SetData<T> and maybe ContainsData<T>? I'd probably lean towards a TryGetData<T> pattern.

I currently use ContainsText and GetText which is then used to create a URI via URI.TryCreate. Unsure if that scenario would work with something like TryGetData<URI>.

paul1956 commented 5 months ago

This is great! Will you also have similar API for SetData<T> and maybe ContainsData<T>? I'd probably lean towards a TryGetData<T> pattern.

I currently use ContainsText and GetText which is then used to create a URI via URI.TryCreate. Unsure if that scenario would work with something like TryGetData<URI>.

@elachlan I think its 2 different applications. If I put text on the clipboard in the form of a valid URI it's still text, if I put a URI on the clipboard its a URI. The question is what happens if I call ContainsData or ContainsText and the clipboard contents is compatible with URI.TryCreate or ToString respectively. I would hope it did the conversion and just worked.