473,394 Members | 1,694 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

Returning values to a method from a switch statement

Ant
Hi, I need to return a value to a methods call from a switch statement nested
in the method. How can this be done?

int myMethod(int someValue)
{

switch (someValue)
{
case(1):
{
return anotherMethod()
}
case(2):
{
return somethingElse()
}
}

}
When I do this, I get a compile error saying, "not all code paths return a
value". I understand why I'm getting this as I'm not returning a value to the
main method. My question is, how do I return the value from the switch?

Thanks in advance
Ant
Dec 1 '05 #1
12 16263
There's nothing wrong with putting a return statement inside a switch.
The reason you're getting that error is because the method won't return
anything if someValue isn't 1 or 2 - there's a possible code path that
leads straight to the end of the method, skipping both return
statements. (Even if you know someValue will always be 1 or 2, the
compiler doesn't know that.)

You can fix it by returning a default value or throwing an exception
after the switch, or adding a default case to the switch and doing it
there:

switch (someValue)
{
case 1:
return anotherMethod();
case 2:
return somethingElse();
default:
throw new ArgumentException("someValue must be 1 or 2");
}

Jesse

Dec 1 '05 #2
KJ
You also need a "default:" statement, since there are more possible
values to someValue than 1 and 2 (what happens if someone calls
myMethod(42)?). Also, the curly braces after each case statement are
superflous, as are the parens around 1 and 2.

Have fun.

Dec 1 '05 #3
Hi Ant,

As a best practice you should try programming using a single point of exit
within your procedures that way you will never walk into problems like you
are facing right now.
So something like this.

int myMethod(int someValue)
{
int result;
switch (someValue)
{
case(1):
{
result = 12;
}
case(2):
{
result = 13;
}
}
return result;
}
Kind Regards,

--
Rainier van Slingerlandt
(Freelance trainer/consultant/developer)
www.slingerlandt.com
"Ant" wrote:
Hi, I need to return a value to a methods call from a switch statement nested
in the method. How can this be done?

int myMethod(int someValue)
{

switch (someValue)
{
case(1):
{
return anotherMethod()
}
case(2):
{
return somethingElse()
}
}

}
When I do this, I get a compile error saying, "not all code paths return a
value". I understand why I'm getting this as I'm not returning a value to the
main method. My question is, how do I return the value from the switch?

Thanks in advance
Ant

Dec 1 '05 #4
This won't work.
You'll get another compile-time error as result may not be initialized...

Happy Coding
- Michael S

"Rainier [MCT]" <Ra********@discussions.microsoft.com> wrote in message
news:64**********************************@microsof t.com...
Hi Ant,

As a best practice you should try programming using a single point of exit
within your procedures that way you will never walk into problems like you
are facing right now.
So something like this.

int myMethod(int someValue)
{
int result;
switch (someValue)
{
case(1):
{
result = 12;
}
case(2):
{
result = 13;
}
}
return result;
}
Kind Regards,

--
Rainier van Slingerlandt
(Freelance trainer/consultant/developer)
www.slingerlandt.com
"Ant" wrote:
Hi, I need to return a value to a methods call from a switch statement
nested
in the method. How can this be done?

int myMethod(int someValue)
{

switch (someValue)
{
case(1):
{
return anotherMethod()
}
case(2):
{
return somethingElse()
}
}

}
When I do this, I get a compile error saying, "not all code paths return
a
value". I understand why I'm getting this as I'm not returning a value to
the
main method. My question is, how do I return the value from the switch?

Thanks in advance
Ant

Dec 1 '05 #5
Rainier [MCT] wrote:
As a best practice you should try programming using a single point of exit
within your procedures that way you will never walk into problems like you
are facing right now.


No, instead you'll run into problems where the code is much harder to
read because you need much more indentation to cope with the fact that
simple "I'm done now" situations aren't just returned from.

I've read a lot of code which followed the "only return from one place"
mentality, and a lot of it was hellish.

Jon

Dec 1 '05 #6
Michael S wrote:
This won't work.
You'll get another compile-time error as result may not be initialized...


Which is absolutely equivalent to the original problem, in fact. So the
code has been made more complex without fixing the problem.
Interesting...

Jon

Dec 1 '05 #7
Plus some fall through errors, but as the compiler catches the problems
with the user error in both methods I don't think that's a reason for
choosing one over the other. Single return can make it easier to avoid
code duplication, but early return for degenerate cases mostly makes
things clearer, as with the typical
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
{
return false;
}
//

It's a pity VS doesn't seem to highlight possible exit points from a
method like some IDEs (maybe I missed it)

Jon Skeet [C# MVP] wrote:
Michael S wrote:
This won't work.
You'll get another compile-time error as result may not be initialized...

Which is absolutely equivalent to the original problem, in fact. So the
code has been made more complex without fixing the problem.
Interesting...

Jon

Dec 1 '05 #8
> It's a pity VS doesn't seem to highlight possible exit points from a
method like some IDEs (maybe I missed it)


CodeRush, a commercial addin for VS, has this among its extensive feature
list.
Dec 1 '05 #9
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:11**********************@g47g2000cwa.googlegr oups.com...
Rainier [MCT] wrote:
As a best practice you should try programming using a single point of
exit
within your procedures that way you will never walk into problems like
you
are facing right now.


No, instead you'll run into problems where the code is much harder to
read because you need much more indentation to cope with the fact that
simple "I'm done now" situations aren't just returned from.

I've read a lot of code which followed the "only return from one place"
mentality, and a lot of it was hellish.

Jon


Agree.

Makes me think of this motto: - Keep it as simple as possible, but no
simpler!
Was it Einstein who said that? Anyone know?

- Michael S
Dec 1 '05 #10
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:11**********************@g47g2000cwa.googlegr oups.com...
Rainier [MCT] wrote:
As a best practice you should try programming using a single point of exit
within your procedures that way you will never walk into problems like you
are facing right now.


No, instead you'll run into problems where the code is much harder to
read because you need much more indentation to cope with the fact that
simple "I'm done now" situations aren't just returned from.

I've read a lot of code which followed the "only return from one place"
mentality, and a lot of it was hellish.


Careful Jon. The Purity Zealots will come and take you away for such blasphemy.
In a Pre-Exception world it was MUCH more important to follow this logic. That way you have all of
your resource cleanup in one place. Ooops, Only cleaned up the resources in 19 of the exit points
instead of 20.
Of course I often broke the *Rule* even then. When I was *Lucky* enough to inherit one of these
messes, I generally refactored the mess into 2 functions. The outer function handled Setup,Error
handling, and Cleanup. The inner function acted like a Sieve that fell through. This put all of my
error handling in one place and all of my Cleanup in one place.
I had a common point of return from the Outer function and a cleaner flow in the inner function.
So, even though I didn't follow the *Rule*, I did address the issues that the *Rule* was meant to
solve.
Amazingly, once Exceptions are taken into account this *Sieve* logic becomes much more
practical(and common). Of course most of the "return"s are replaced by exceptions, but the concept
is the same.
try/finally for setup/cleanup
try/catch for error handling.

Even though I won't hesitate to use a *Sieve* in my code MOST of my methods follow the "single point
of return" methodology. This mainly comes from a desire to maintain flow control. For instance, if I
want to ensure that ALL code paths (except nasty exceptions) flow through a given point, so I can
put in tracing or something.

In general, if the logic flow doesn't get too convoluted I will use a single point of return,
but I won't lose any sleep over implementing a *Sieve*.

Bill

Dec 2 '05 #11
Ant
Thanks everyone. Phew!

I ended up just using a default & including an exeption in it. (Whosever
idea that was, thanks). As for single point of exit, I just used the return
of each. It works fine & isn't difficult to read.
Thaks for all your thoughts
Ant

"Bill Butler" wrote:
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:11**********************@g47g2000cwa.googlegr oups.com...
Rainier [MCT] wrote:
As a best practice you should try programming using a single point of exit
within your procedures that way you will never walk into problems like you
are facing right now.


No, instead you'll run into problems where the code is much harder to
read because you need much more indentation to cope with the fact that
simple "I'm done now" situations aren't just returned from.

I've read a lot of code which followed the "only return from one place"
mentality, and a lot of it was hellish.


Careful Jon. The Purity Zealots will come and take you away for such blasphemy.
In a Pre-Exception world it was MUCH more important to follow this logic. That way you have all of
your resource cleanup in one place. Ooops, Only cleaned up the resources in 19 of the exit points
instead of 20.
Of course I often broke the *Rule* even then. When I was *Lucky* enough to inherit one of these
messes, I generally refactored the mess into 2 functions. The outer function handled Setup,Error
handling, and Cleanup. The inner function acted like a Sieve that fell through. This put all of my
error handling in one place and all of my Cleanup in one place.
I had a common point of return from the Outer function and a cleaner flow in the inner function.
So, even though I didn't follow the *Rule*, I did address the issues that the *Rule* was meant to
solve.
Amazingly, once Exceptions are taken into account this *Sieve* logic becomes much more
practical(and common). Of course most of the "return"s are replaced by exceptions, but the concept
is the same.
try/finally for setup/cleanup
try/catch for error handling.

Even though I won't hesitate to use a *Sieve* in my code MOST of my methods follow the "single point
of return" methodology. This mainly comes from a desire to maintain flow control. For instance, if I
want to ensure that ALL code paths (except nasty exceptions) flow through a given point, so I can
put in tracing or something.

In general, if the logic flow doesn't get too convoluted I will use a single point of return,
but I won't lose any sleep over implementing a *Sieve*.

Bill


Dec 2 '05 #12
Bill... Single entry, single exit, AKA SESE, seems to work for you and
has kept you out of trouble so go with it, but SESE is no longer a
coding standard in C++. C++ Coding Standards Herb Sutter, Andrei
Alexandrescu page 3. So I am not sure any zealot will complain in C#.

Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***
Dec 2 '05 #13

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

Similar topics

37
by: Thomas Matthews | last post by:
Hi, My son is writing a program to move a character. He is using the numbers on the keypad to indicate the direction of movement: 7 8 9 4 5 6 1 2 3 Each number has a direction except...
4
by: Roy Gourgi | last post by:
Hi, My program has to be able to call on many classes that differ only by a number and rather than use a switch statement I was wandering if it is possible to do it in C# as it is possible in...
24
by: Mark | last post by:
Hi - how can I get a switch statement to look for a range of values? I have: function payCalc(field, field2) switch(field.value) { case 0-50: field2.value="lower band"; case 51-99:...
19
by: rdavis7408 | last post by:
Hello, I have four textboxes that the user enters the price per gallon paid at the pump, the mileage per gallon and I would like to then calculate the cost per gallon and use a switch statement to...
4
by: priyanka | last post by:
Hi there, I had a question. Is there any way of testing a string value in a switch statement. I have about 50 string values that can be in a string variable. I tried cheking them with the if...
1
by: Angel Of Death | last post by:
I have a method. It takes some XML as a parameter. Depending on the content of the XML it should create a specific object and call a KNOWN method. So: public void PersistXml(string XmlData){} ...
6
by: asadikhan | last post by:
Hello, I have a bit of a design issue around this application I am developing, and I just want to run it through some of the brains out here. So I have a table called ErrorCheck which...
2
by: Miyagi | last post by:
I have a bunch of conditions in which to determine different types of questions to ask in a survey I am constructing. Just was wondering if anybody has used a two-dimensional switch statement. If...
1
by: Frakes | last post by:
I'm using a hyperlink to pass a value from a home page to a search page. I'm using to values to identify and display only certain input/select boxs that relate to whatever unique search the user...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...

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.