Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
public String getage(int age)
        {
            if (age > 60)               //  Error : Not all code paths return a value.
                return "senior";
            else
                if (age >= 40 && age <= 59)
                    return "middle aged";
                else
                    if (age >= 20 && age <= 39)
                        return "adult";
                    else
                        if (age >= 12 && age <= 19)
                            return "teenaged";
        }




it do not get the error in it..please help a newbee..thx
Posted
Comments
Ankur\m/ 25-Dec-10 5:13am    
You need an else condition. Or just add 'return ""' at the last.
#realJSOP 25-Dec-10 7:14am    
Don't vote correct answers with a 1. It may not be the answer you wanted, but they ARE correct based on your question.

Your If-case does not handle the scenario if age is less than 12. Look closely. Thus, for age < 12, your code does not return anything and hence the error.
 
Share this answer
 
I guess, you are trying to know the reason of the error message.

As your method returns a String, the complier expects that each and every condition should return a String.

Look the following piece of code in your example:

C#
if (age >= 12 && age <= 19)
     return "teenaged";


It doesn't have an "else" block, so, the compiler doesn't see any String value getting returned in this situation. So, it is not able to compile the class and showing the error.

I hope I was able to help you.
 
Share this answer
 
Shikhar,

You already received enough answers; they tell you that you need "else" and this is all correct.

However, I personally think this is just a technical detail.

You problem is rather conceptual: you ignore children (totally, with newborn, infants...), but you should not. Unlike most of the software developers, children still have unclouded mind.

So, here is an ultimate answer for you: if you just accidentally forgot about "else" -- add it, if you ignore children -- rethink your life.

Best wishes! ;)
 
Share this answer
 
v3
Comments
JF2015 25-Dec-10 12:41pm    
Although the OP might not say this answer was very helpful, I like the way you think. Have my 5.
Sergey Alexandrovich Kryukov 25-Dec-10 16:57pm    
Better take look at my recent Answer with AgeLimitException -- it makes sense; something important we all forgot. Should be noted...
Espen Harlinn 26-Feb-11 11:24am    
Good reply - my 5
Sergey Alexandrovich Kryukov 26-Feb-11 17:54pm    
Or, it's my old post about children!
Thank you, Espen!
--SA
C#
public String getage(int age)        
{            
  if (age > 60) //  Error : Not all code paths return a value.                
    return "senior";            
  else
    if (age >= 40 && age <= 59)                    
      return "middle aged";                
    else
      if (age >= 20 && age <= 39)                         
        return "adult";                    
      else
        if (age >= 12 && age <=19)                            
          return "teenaged";
        else
          return "else";      
}


This code should not cause the error. It handles every case that could occur.
 
Share this answer
 
v4
Comments
shikhar gilhotra 25-Dec-10 4:34am    
this is a tricky but incorrect answer.....pls help aainest my query..thx
JF2015 25-Dec-10 4:49am    
If this doesn't help you, then you need to tell us in more detail what you want.
#realJSOP 25-Dec-10 8:14am    
I voted your question up to counteract the idiot's invalid 1 vote.
Manfred Rudolf Bihy 25-Dec-10 9:05am    
Same from me 5+
Still the first that should have been pointed out to OP is the single point of entry single point of exit thing.
Sergey Alexandrovich Kryukov 25-Dec-10 15:52pm    
There was a vote of 1? Right, what a stupidity! I'm counteracting, too!
Your complete condition looks "not so good" maybe you try something like this.

C#
public string GetAge(int age)
 {
     if (age >= 60)
         return "senior";
     if (age >= 40)
         return "middle aged";
     if (age >= 20)
         return "adult";
     if (age >= 12)
         return "teenaged";
     // now all code paths will return a string - compiler satisfied
     return "child";
 }
 
Share this answer
 
v4
Comments
#realJSOP 25-Dec-10 8:14am    
I voted your question up to counteract the idiot's invalid 1 vote.
Manfred Rudolf Bihy 25-Dec-10 9:04am    
Ditto 5+
pasztorpisti 25-Dec-10 11:17am    
Removed the unnecessary 'else' keywords to make it more readable. I think that embedded branching always make code unreadable, so this is definately the best answer. A similar scenario is when someone uses embedded if-else branches to check something inside a loop. In that case the unreadable code can be avoided with 'continue' statements similarly to the returns here. If someone needs 'single point of exit' function then the embedded if-else branches is the way to go but we usually follow the rule of putting braces around both the if and else codeblocks if one of them is consisting more then 1 line of code.
pasztorpisti 25-Dec-10 12:42pm    
@johannesnestler: Don't use hungarian notation. Iam hungarian, and I know its bad! :) Maybe the "p" prefix for pointers can be useful but you can live even without that!
Sergey Alexandrovich Kryukov 25-Dec-10 13:23pm    
pasztorpisti, I support your point about not using "else", even though the extra assignment can be considered more redundant than that, but it adds to supportability and readability (I'm afraid some readers of such could will be irritated).

I know that hungarian language is one of the most complex and hard-to-learn (maybe even in comparison with my native language, I don't know), but I've read a few (really great) hungarian books in translation and could naturally feel the wonderful richness of the language even after translation. To the opposite case, hungurian notation served as a week tool to compensate the extreme lame of the languages with poor typing model, such as C and, in fact, C++ (how much more reasons for further irritation!).

Thank you.
Try this:

C#
public string getage(int age)
{
    string result = "senior";
    result = (age < 60) ? "middle aged" : result;
    result = (age < 40) ? "adult"       : result;
    result = (age < 20) ? "teenaged"    : result;
    result = (age < 13) ? "child"       : result;
    return result;
}


No matter what happens, a string will be returned. Your particular problem is that you need an else after the last if statement that returns an appropriate string indicating an error condition.



EDIT =============

Corrected for reverse logic.
 
Share this answer
 
v4
Comments
Manfred Rudolf Bihy 25-Dec-10 9:06am    
Clear and concise! 5+
Single point of exit, that's how I like my functions! :)
pasztorpisti 25-Dec-10 11:29am    
Single point of exit is good for lenghty functions with fancy logic, but in such a simple function its better to use a few checks and returns like johannesnestler did below. It makes code more readable. And this code performs a few unnecessary assignments, so I gave a 4.

EDIT: Just changed my vote to 1 because I found out that the code isn't working. It gives you "middle aged" even if age is 1!
JF2015 25-Dec-10 17:41pm    
Have my 4, since although the code doesn't work it showed the OP how it should be done - he could figure out the logic on his own.
Sandeep Mewara 26-Dec-10 0:50am    
Looks like in a hurry you made a small mistake. For example, Age 10 will pass as true for all the conditions and it will return 'middle aged' at the end all the time!
#realJSOP 26-Dec-10 5:49am    
@everyone that noticed - I fixed the reverse logic thing. I apologize if the mistake caused rivers to overflow their banks, or cities to crumble under the weight of such a grievous error. However, if there has been even one regime change via violent overthrow, you can't blame that on me.

Missing case



Now I understand that there can be another valid use case.
This is maybe what Shikhar really wanted but failed to express.

Forgive me Shikhar! May be you're not ignoring children; may be you're -- just the opposite -- overly protective if them?

Forgive me, everyone! Silly me!

We all missed yet another important option.
Here is how:

C#
public class AgeLimitException : System.ApplicationException {
    internal AgeLimitException(
         int actualAge,
         string comment) : base(comment) {
              this.fActualAge = actualAge;
    } //AgeLimitException
    internal AgeLimitException(int actualAge) {
        this.fActualAge = actualAge;
    } //AgeLimitException
    public int ActualAge { get { return fActualAge; } }
    int fActualAge;
} //class AgeLimitException

//...

public string GetAgeString(int age) {
    if (age > 60)
        return "senior";
    else if (age >= 40 && age <= 59)
        return "middle aged";
    else if (age >= 20 && age <= 39)
        return "adult";
    else if (age >= 12 && age <= 19)
         return "teenaged";
    else
         throw new AgeLimitException(age,
             "Parential consent required");
} //GetAgeString


Beyond the jokes: this is another valid use case of not returning in every case: throwing an exception.

Thank you. ;)
 
Share this answer
 
Comments
fjdiewornncalwe 25-Dec-10 19:01pm    
Nice catch... I agree with you, but I don't know why you were not voted well for the answer. I'm never quite sure why a "3" vote makes any sense unless it is someone trying to get their own answer to show higher on the list without being really blatant about it.
Sergey Alexandrovich Kryukov 25-Dec-10 22:18pm    
Marcus, I don't understand you: who do you think voted "3" for what? I did not...
I have no idea who voted 3 for my answer; and I would not see any reason; I would suggest that not very good vote needs proper honest comments pointing out the problems of the post, so it could be argued. Whatever...
Sergey Alexandrovich Kryukov 26-Feb-11 14:39pm    
I misplaced my comment to yours a while ago, above...
--SA
Espen Harlinn 26-Feb-11 11:28am    
Another good effort - my 5
Sergey Alexandrovich Kryukov 26-Feb-11 14:40pm    
Thank you.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900