0

I am attempting to convert a string value passed along with the "Tag" property of a button to custom type "DialogClosingEventArgs" as shown:

var converted = (DialogClosingEventArgs)((Button)sender).Tag;

However during runtime I get the following exception: "Unable to cast object of type 'System.String' to type 'MaterialDesignThemes.Wpf.DialogClosingEventArgs'"

How can I force this conversion?

user3342256
  • 1,238
  • 4
  • 21
  • 35
  • It's not possible to cast a `string` to `DialogClosingEventArgs` and there is no way of doing that as those are two completely different types – Fabjan Jun 03 '18 at 18:17
  • Why are you attempting that particular cast? Did you expect the object in the tag to *be* an object of that type? Was the string unexpected? Please elaborate on why you think "forcing" this cast would even be possible. – Lasse V. Karlsen Jun 03 '18 at 18:44

1 Answers1

0

To cast an object to a type, it must be compatible with the type you cast. As you say, it is a string so simply it is not Castable to DialogClosingEventArgs.

Works:

button.Tag = 3;
int a = (int)button.Tag;

Doesn't Work:

button.Tag = "some string";
int a = (int)button.Tag;

Because string cannot be cast to int.

Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171