473,804 Members | 2,998 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to change these ifs to switch

Hi

I was wondering if someone could help me change these ifs to a switch
statement. I tried but I can't make it work.

Thanks Tim
Code below:

protected void SetThisControl( System.Web.UI.C ontrol WebControl1)

{

if (WebControl1 is BaseValidator)

{

//Do stuff

}

if (WebControl1 is Label)

{

//Do something

}

if (WebControl1 is Button)

{

//Do something

}

if (WebControl1 is DataGrid)

{

//Do something

}
}
Nov 16 '05 #1
7 5522
Tim Cowan wrote:
Hi

I was wondering if someone could help me change these ifs to a switch
statement. I tried but I can't make it work.
as i know switch accepts integral type only,
if not this code should work i think, but as i said earlier I DONT THINK
this is possible,

switch(WebContr ol1.GetType())
{
case typeof(System.W eb.UI.WebContro ls.BaseValidato r):
MessageBox.Show ("this is web validator");
case etc...

}
Thanks Tim
Code below:

protected void SetThisControl( System.Web.UI.C ontrol WebControl1)

{

if (WebControl1 is BaseValidator)

{

//Do stuff

}

if (WebControl1 is Label)

{

//Do something

}

if (WebControl1 is Button)

{

//Do something

}

if (WebControl1 is DataGrid)

{

//Do something

}
}

Nov 16 '05 #2
Tim,

You would have to switch on the type name, which isn't truly accurate
(theoretically, you could have a type name which is the same between two
types, but they reside in different assemblies).

For comparisons against types, I would recommend using the if statement,
as you have there. You can't switch on reference types (with the exception
of strings) in a switch statement, so you will have to use the if statement.

To make it look better, I would recommend refactoring the code so that
it looks like this:

protected void SetThisControl( System.Web.UI.C ontrol WebControl1)
{
BaseValidationA ction(WebContro l1);
LabelAction(Web Control1);
ButtonAction(We bControl1);
DataGridAction( WebControl1);
}

And then, each function would look like this:

BaseValidationA ction(System.We b.UI.Control webControl)
{
// If the control is the right type, continue.
if (webControl as BaseValidator == null)
{
// Get out.
return;
}
}

If you want to get really fancy, I would name the methods in a manner
that relates to the type that is being processed, then use reflection to
make the call to the appropriate method (based on the type). This would
eliminate the need for the check in each function, and make the code in
SetThisControl more descriptive (instead of making needless calls).

Hope this helps.

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Tim Cowan" <ti**********@p eopletogo.com> wrote in message
news:Ob******** ***********@new s20.bellglobal. com...
Hi

I was wondering if someone could help me change these ifs to a switch
statement. I tried but I can't make it work.

Thanks Tim
Code below:

protected void SetThisControl( System.Web.UI.C ontrol WebControl1)

{

if (WebControl1 is BaseValidator)

{

//Do stuff

}

if (WebControl1 is Label)

{

//Do something

}

if (WebControl1 is Button)

{

//Do something

}

if (WebControl1 is DataGrid)

{

//Do something

}
}

Nov 16 '05 #3
sorry there was a problem at my previouse message

as i know switch accepts integral type only,
if not this code should work i think, but as i said earlier I DONT THINK
this is possible,

switch(WebContr ol1.GetType())
{
case typeof(System.W eb.UI.WebContro ls.BaseValidato r):
MessageBox.Show ("this is web validator");
case etc...

}

Erdem
Nov 16 '05 #4

"Tim Cowan" <ti**********@p eopletogo.com> wrote in message
news:Ob******** ***********@new s20.bellglobal. com...
Hi

I was wondering if someone could help me change these ifs to a switch
statement. I tried but I can't make it work.

Thanks Tim
Code below:

protected void SetThisControl( System.Web.UI.C ontrol WebControl1)

{

if (WebControl1 is BaseValidator)

{

//Do stuff

}

if (WebControl1 is Label)

{

//Do something

}

if (WebControl1 is Button)

{

//Do something

}

if (WebControl1 is DataGrid)

{

//Do something

}
}

Here's one possibility (there may well be better ones).
The WebControl class has a GetType method available that will return an
instance of class Type indicating the type of control in question. In turn,
class Type exposes a property FullName which gives you the name of the
control type as a String. More specifically, it :
<quote>
Gets the fully qualified name of the Type, including the namespace of the
Type.

</quote>

As the C# switch construct can accept either integral value or string type
expressions as the switch expression, you should be able to use the FullName
property (or some portion thereof) as the switch expression.

Hopefully, there's a simpler way and somebody else will post it :-)
--
Peter [MVP Visual Developer]
Jack of all trades, master of none.
Nov 16 '05 #5
"Tim Cowan" <ti**********@p eopletogo.com> wrote:
I was wondering if someone could help me
change these ifs to a switch statement.
I tried but I can't make it work.


You'd need to do something like 'switch (ctl.GetType()) ', but that's
not permitted because data types are not integral types.

If the set of ifs is a real problem for you, polymorphism is an
option. You could inherit from the necessary controls, make your
inherited versions implement an interface ISomething (with a method M
that does whatever your current code is trying to do to each control),
pass your control as an ISomething, and call M on it.

P.
Nov 16 '05 #6

"Peter van der Goes" <p_**********@t oadstool.u> wrote in message
news:%2******** ********@TK2MSF TNGP15.phx.gbl. ..

Here's one possibility (there may well be better ones).
The WebControl class has a GetType method available that will return an
instance of class Type indicating the type of control in question. In turn, class Type exposes a property FullName which gives you the name of the
control type as a String. More specifically, it :
<quote>
Gets the fully qualified name of the Type, including the namespace of the
Type.

</quote>

As the C# switch construct can accept either integral value or string type
expressions as the switch expression, you should be able to use the FullName property (or some portion thereof) as the switch expression.

Hopefully, there's a simpler way and somebody else will post it :-)
--
Peter [MVP Visual Developer]
Jack of all trades, master of none.

FWIW, I just ginned up a little test app using the technique above and it
works fine.
The string returned from the FullName property is like:
"System.Web.UI. WebControls.Lab el" for a label.
First create an instance of class Type to hold the results of the call to
the GetType method, then capture the FullName property of your Type object
in a string
Example:

Type a;

a = CheckBox1.GetTy pe();

String aa = a.FullName;

Peter [MVP Visual Developer]
Jack of all trades, master of none.

Nov 16 '05 #7
Actually, it would be impossible (*) to replace it with a switch
statement. The problem is the line:
if (WebControl1 is BaseValidator)
Now, since BaseValidator is an abstract class WebControl1 cannot be a
BaseValidator; it has to be a derived class. So if you were to do what
other here suggest, namely:

switch(WebContr ol1.GetType().F ullName)
case "System.Web.UI. WebControls.Bas eValidator":

You'll never get a match.

Continue with the if() statements. That is precisely what the "is" operator
is designed for.
(*) OK, a possibly sufficient approximation IS possible, but it's ugly:
switch(WebContr ol1.GetType().F ullName)
case "System.Web.UI. WebControls.Reg ularExpressionV alidator":
case "System.Web.UI. WebControls.Req uiredFieldValid ator":
case "System.Web.UI. WebControls.Com pareValidator":
case "System.Web.UI. WebControls.Ran geValidator":
/* Be sure to include cases for any class you derived from
CustomValidator
*/
/*
Do Stuff
*/
--
Truth,
James Curran
[erstwhile VC++ MVP]
Home: www.noveltheory.com Work: www.njtheater.com
Blog: www.honestillusion.com Day Job: www.partsearch.com
Nov 16 '05 #8

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

Similar topics

4
50261
by: Nothing | last post by:
I have a form that I send to a printer. The workstation that is using the DB has more then one printer defined. The default is NOT the printer that I want to use for output from the report/form. How do I send the out of a report, using VBA, to a specific printer? Michael Charney *** Sent via Developersdex http://www.developersdex.com *** Don't just participate in USENET...get rewarded for it!
31
2819
by: Bill Cunningham | last post by:
There must be some change in the standard because I ran into this error when I put this line in a header. # pragma once I only wanted the headers to be included once. The compiler said something about obsolete. -----= Posted via Newsfeeds.Com, Uncensored Usenet News =-----
5
7500
by: Charles F McDevitt | last post by:
I'm converting some old programs that use old iostreams. In one program, the program is using cout to output to the stdout stream. Part way through, the program wants to put some binary data out, and changes the iostream to binary like this: cout << "this is text" << eol; binary(cout); cout << "this is binary" << eol; text(cout); cout << "back to text mode" << eol;
6
3121
by: Michelle Stone | last post by:
Hi I am doing a bilingual .NET application for English/Arabic. On a web form, I have some edit boxes for data entry in Arabic and some for entry in English. Right now the user has to change his keyboard language by pressing ALT+SHIFT (or by changing the language manually elsewhere) each time he wants to shift from one language to another.
4
7032
by: Michael Hannon | last post by:
Greetings. We're running Postgres 7.3 on an Intel linux box (Redhat Enterprise server, version 3.0). We find ourselves in an awkward position: we have a database of attributes relating to students that uses as its primary key the ID number of the student. This is awkward for the following reasons. Our university used to use social-security numbers for student ID's. They stopped doing that a few years ago, but didn't force the change...
26
2087
by: Protoman | last post by:
I've written this program that simulates a 36 character, 10 rotor reciprocal rotor cipher, w/ a plugboard. Any way I can make the plugboard function more compact and/or be able to change the mapping at runtime? char Enigma::plugboard(char Char) { if(Char=='A') return '0'; else if(Char=='B')
4
2439
by: gregincolumbus | last post by:
I am trying to get the financial calculation on this to trigger whenever there is a change to select1. Right now, the user has to click on select2 to trigger the changes. Ideally, a change of select1 1. trigger the population of select2 (and set it initially to 0) 2. make the text fields disappear 3. trigger the financial calculation to reflect the select1 choice. Any help would be greatly appeciated !
4
4218
by: =?Utf-8?B?bXVzb3NkZXY=?= | last post by:
Hi peeps I'm trying to change the default postback of my webpage. I'm trying to create a searchbox where you can just press enter and it goes to the search results (ala apple.com *ahem* :o) However, the page just postsback to itself when I hit enter. Is there any way to change the default postback behaviour for a page?! I'm using .net 3.5
56
6786
by: Adem | last post by:
C/C++ language proposal: Change the 'case expression' from "integral constant-expression" to "integral expression" The C++ Standard (ISO/IEC 14882, Second edition, 2003-10-15) says under 6.4.2(2) : case constant-expression : I propose that the case expression of the switch statement be changed from "integral constant-expression" to "integral expression".
0
9706
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
9579
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
10332
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
10077
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...
1
7620
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5522
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4300
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
2
3820
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2991
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.