G
GiJeet
Problem using AS operator to cast Tag property
Hello, I’m using the Tag property of a menu item to hold an enum value
of a PictureBoxSizeMode.
Eg: this.menuImageStretch.Tag =
System.Windows.Forms.PictureBoxSizeMode.StretchImage;
now in the ProcessImageClick method I check to make sure the Tag
propety is not null and cast from type Object to PictureBoxSizeMode
enum. The code below works as long as the value in Tag is
PictureBoxSizeMode enum value but when not...error.
private void ProcessImageClick(ToolStripItemClickedEventArgs e)
{
ToolStripItem item = e.ClickedItem;
if (item.Tag != null)
{
pbxPhoto.SizeMode = (System.Windows.Forms.PictureBoxSizeMode)
item.Tag;
}
}
However, since the Tag property is of type object it can hold ANY
value so I want to prevent a runtime error and us the AS operator to
cast the tag property value to type
System.Windows.Forms.PictureBoxSizeMode but it throws an error: Error
1 The as operator must be used with a reference type
('System.Windows.Forms.PictureBoxSizeMode' is a value type)
so if I use: item.Tag as System.Windows.Forms.PictureBoxSizeMode //
throws error above
How to cast beforehand to prevent runtime error?
Thx
G
Hello, I’m using the Tag property of a menu item to hold an enum value
of a PictureBoxSizeMode.
Eg: this.menuImageStretch.Tag =
System.Windows.Forms.PictureBoxSizeMode.StretchImage;
now in the ProcessImageClick method I check to make sure the Tag
propety is not null and cast from type Object to PictureBoxSizeMode
enum. The code below works as long as the value in Tag is
PictureBoxSizeMode enum value but when not...error.
private void ProcessImageClick(ToolStripItemClickedEventArgs e)
{
ToolStripItem item = e.ClickedItem;
if (item.Tag != null)
{
pbxPhoto.SizeMode = (System.Windows.Forms.PictureBoxSizeMode)
item.Tag;
}
}
However, since the Tag property is of type object it can hold ANY
value so I want to prevent a runtime error and us the AS operator to
cast the tag property value to type
System.Windows.Forms.PictureBoxSizeMode but it throws an error: Error
1 The as operator must be used with a reference type
('System.Windows.Forms.PictureBoxSizeMode' is a value type)
so if I use: item.Tag as System.Windows.Forms.PictureBoxSizeMode //
throws error above
How to cast beforehand to prevent runtime error?
Thx
G