473,748 Members | 10,048 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help: The as operator must be used with a reference type ??

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 PictureBoxSizeM ode.

Eg: this.menuImageS tretch.Tag =
System.Windows. Forms.PictureBo xSizeMode.Stret chImage;

now in the ProcessImageCli ck method I check to make sure the Tag
propety is not null and cast from type Object to PictureBoxSizeM ode
enum. The code below works as long as the value in Tag is
PictureBoxSizeM ode enum value but when not...error.

private void ProcessImageCli ck(ToolStripIte mClickedEventAr gs e)
{
ToolStripItem item = e.ClickedItem;
if (item.Tag != null)
{
pbxPhoto.SizeMo de = (System.Windows .Forms.PictureB oxSizeMode)
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.PictureBo xSizeMode but it throws an error: Error
1 The as operator must be used with a reference type
('System.Window s.Forms.Picture BoxSizeMode' is a value type)

so if I use: item.Tag as System.Windows. Forms.PictureBo xSizeMode //
throws error above

How to cast beforehand to prevent runtime error?

Thx
G
Nov 13 '08 #1
6 8442
It happens that GiJeet formulated :
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 PictureBoxSizeM ode.

Eg: this.menuImageS tretch.Tag =
System.Windows. Forms.PictureBo xSizeMode.Stret chImage;

now in the ProcessImageCli ck method I check to make sure the Tag
propety is not null and cast from type Object to PictureBoxSizeM ode
enum. The code below works as long as the value in Tag is
PictureBoxSizeM ode enum value but when not...error.

private void ProcessImageCli ck(ToolStripIte mClickedEventAr gs e)
{
ToolStripItem item = e.ClickedItem;
if (item.Tag != null)
{
pbxPhoto.SizeMo de = (System.Windows .Forms.PictureB oxSizeMode)
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.PictureBo xSizeMode but it throws an error: Error
1 The as operator must be used with a reference type
('System.Window s.Forms.Picture BoxSizeMode' is a value type)

so if I use: item.Tag as System.Windows. Forms.PictureBo xSizeMode //
throws error above

How to cast beforehand to prevent runtime error?

Thx
G
You could test with the "is" operator whether that Tag really holds a
PictureBoxSizeM ode.

An other option could be (C#2 and on)

pbxPhoto.SizeMo de = item.Tag as PictureBoxSizeM ode? ??
PictureBoxSizeM ode.Normal;

That is:
* use "as" to cast to a Nullable<Pictur eBoxSizeMode>,
* then use the "??" operator to convert a possible null value to a
default value (I have chosen "Normal")

Hans Kesting
Nov 13 '08 #2
>On Nov 13, 8:53*am, Hans Kesting <news.han...@sp amgourmet.comwr ote:
That is:
* use "as" to cast to a Nullable<Pictur eBoxSizeMode>,
* then use the "??" operator to convert a possible null value to a *
default value (I have chosen "Normal")
Hans, thanks for responding. I'm a little confused. I see 3 question
marks...please explain.
Thanks again!
G
Nov 13 '08 #3
I'm a little confused. I see 3 question marks...please explain.

Ooh, that is evil...

PictureBoxSizeM ode? means Nullable<Pictur eBoxSizeMode- i.e. it can be
either a PictureBoxSizeM ode or null (but nothing else).

?? is the null-coalescing operator; the first non-null value is used as
the result.

To be honest, I probably would *not* recommend the use of the suggested
syntax:

as {type}? ?? {default};

While terse (and quite clever), IMO this adds confusion. Which is never
a good idea. I would simply use the longer:

PictureBoxSizeM ode result;
if(val != null && val is PictureBoxSizeM ode) {
result = (PictureBoxSize Mode) val;
} else {
result = PictureBoxSizeM ode.Normal; // etc
}

YMMV

Marc
Nov 13 '08 #4
Marc Gravell wrote:
>I'm a little confused. I see 3 question marks...please explain.

Ooh, that is evil...

PictureBoxSizeM ode? means Nullable<Pictur eBoxSizeMode- i.e. it can
be either a PictureBoxSizeM ode or null (but nothing else).

?? is the null-coalescing operator; the first non-null value is used
as the result.

To be honest, I probably would *not* recommend the use of the
suggested syntax:

as {type}? ?? {default};
This should be clearer:

(... as Nullable<{type} >).GetValueOrDe fault(...);
>
While terse (and quite clever), IMO this adds confusion. Which is
never a good idea. I would simply use the longer:

PictureBoxSizeM ode result;
if(val != null && val is PictureBoxSizeM ode) {
result = (PictureBoxSize Mode) val;
} else {
result = PictureBoxSizeM ode.Normal; // etc
}

YMMV

Marc

Nov 13 '08 #5
>On Nov 13, 9:44*am, Marc Gravell <marc.grav...@g mail.comwrote:
Ooh, that is evil...
sorry...want's trying to be "evil", just confused.
thanks for all your help.
Nov 13 '08 #6
"GiJeet" <gi****@yahoo.c omwrote in message
news:88******** *************** ***********@o4g 2000pra.googleg roups.com...
>On Nov 13, 9:44 am, Marc Gravell <marc.grav...@g mail.comwrote:
>Ooh, that is evil...
sorry...want's trying to be "evil", just confused.
thanks for all your help.
No, he meant the ? ?? syntax was evil.
Nov 13 '08 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
2122
by: Roger Leigh | last post by:
I've written a simple container template class to contain a single value. This emits a signal when the value is changed (it's used as a notifier of changes), and listeners can connect to its changed signal. i.e. field<int> i(2); i = 4; // field<int>::m_value = 4; changed signal is emitted. Currently, the contained value may be accessed via get_value() and set_value() methods, and for ease of use, operator= and some type conversions...
5
2146
by: xuatla | last post by:
Hi, I encountered the following compile error of c++ and hope to get your help. test2.cpp: In member function `CTest CTest::operator+=(CTest&)': test2.cpp:79: error: no match for 'operator=' in '*this = CTest::operator+(CTest&)((+t2))' test2.cpp:49: error: candidates are: CTest CTest::operator=(CTest&) make: *** Error 1
7
2391
by: Alan Bashy | last post by:
Please, guys, In need help with this. It is due in the next week. Please, help me to implement the functions in this programm especially the first three constructor. I need them guys. Please, help me. This was inspired by Exercise 7 and Programming Problem 8 in Chapter 3 of our text. I have done Exercise 7 for you: Below you will find the ADT specification for a string of characters. It represents slightly more that a minimal string...
47
3357
by: Roger Lakner | last post by:
I often see operator implemented something like this: class Foo { ... }; class FooList { public: const Foo& operator (unsigned index) const {return array;}; Foo& operator (unsigned index) {return
13
2099
by: Protoman | last post by:
Here's a non intrusive reference counting smart pointer class I'm working on; I keep getting a "22 C:\Dev-Cpp\SmrtPtr.hpp ISO C++ forbids declaration of `SmrtPtrDB' with no type" error. Code: SmrtPtr.hpp #pragma once
6
3548
by: Bill foust | last post by:
I'm running into a situation there I think an operator overload would solve the issue, but I'm unable to make it work for some reason. If anyone can help here I would appreciate it. I have a base class that is common to many other classes. public class Base .... end class I have 2 seperate classes that inherit from base
5
2293
by: raylopez99 | last post by:
I need an example of a managed overloaded assignment operator for a reference class, so I can equate two classes A1 and A2, say called ARefClass, in this manner: A1=A2;. For some strange reason my C++.NET 2.0 textbook does not have one. I tried to build one using the format as taught in my regular C++ book, but I keep getting compiler errors. Some errors claim (contrary to my book) that you cannot use a static function, that you must...
19
3527
by: C++Liliput | last post by:
I have a custom String class that contains an embedded char* member. The copy constructor, assignment operator etc. are all correctly defined. I need to create a map of my string (say a class called MyString) and an integer i.e. std::map<MyString, int>. Whenever I insert the elements in the map using the subscript operator, I noticed that the copy constructor for MyString is invoked more number of times than if I do it using the insert()...
2
10040
by: hcaptech | last post by:
This is my Test.can you help me ? 1.Which of the following statement about C# varialble is incorrect ? A.A variable is a computer memory location identified by a unique name B.A variable's name is used to access and read the value stored in it C.A variable is allocated or deallocated in memory during runtime D.A variable can be initialized at the time of its creation or later 2. The.……types feature facilitates the definition of classes...
0
8989
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8828
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9537
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9367
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9243
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8241
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4869
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3309
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2213
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.