I've tried google, and the advance search here. No luck.
Class SomeClass
{
public string MethodName()
{
//Some Code
While(conditions)
{
//More Code
string X;
X = "string stuff";
return X;
}
}
}
I get a 'not all code paths return a value' error. I'm sure I can work around this but I'd like to know how to solve this for future reference.
Think if while loop condition is not met, would your method return string? So put the return just before end of method to ensure that your method will always return string, this MSDN error page not all code paths return a value would further help you to understand.
I believe the sample code is just to show the problem as it does not make much sense to me.
public string MethodName()
{
//Some Code
While(conditions) {
//More Code
string X;
X = "string stuff";
return X;
}
return "somestringifnotX";
}
You are getting error because you are trying to return value from while loop which is not possible
Problem here if your while loop condition is not satisfied than no value get return that is the reason compiler giving you error.
Solution to this is , return empty string outside while loop that you function is returning value.
public string functionname
{
while(conditions)
{
//More Code
string X;
X = "string stuff";
return X;
}
return string.Empty;
}
The problem is that the compiler believes there is a path where conditions is NOT met on the first time it hits the while:
//Some Code
while(conditions)
{
//More Code
string X;
X = "string stuff";
return X;
}
.. Problem!
return "not found"; // or throw new Exception("I'm not supposed to be here")
What you need to do is also return (or throw!) in the instance where conditions aren't met at all.
I think you mean this
static void Main(string[] args)
{
for (int i = 0; i < MethodName().Count; i++ )
{
var result = MethodName()[i] as string;
Console.WriteLine(result);
}
Console.ReadLine();
}
private static List<string> MethodName()
{
var items = new List<string>();
while (Condition)
{
items.Add("SString to return");
}
return items;
}
I hope it will help
Your problem is that you will not return anything when you don't pass your while loop
Class SomeClass
{
public string MethodName()
{
//Some Code
While(conditions)
{
//More Code
string X;
X = "string stuff";
return X;
}
return "Nothing to return Actually";
//OR
Throw new Exception("Conditions where false");
}
}
Imagine you're conditions = false and you never entered the while. This means you will never get to the return. your function on the other hand needs one. End your statement with a return or throw an error when you don't want that behaviour.
public static string binarySearch(int [] dataArray, int dataDicari)
{
int first = 0;
int last = list.length – 1;
int mid;
while (first <= last)
{
mid = (first+last)/2;
if (dataArray[mid] == dataDicari)
return ......; //ISIAN 1
else if (dataArray[mid] < dataDicari)
first = mid + 1;
else if (dataArray[mid] > dataDicari)
last = mid – 1;
}
return .....; //ISIAN 2
}
Related
I have written a c# extension method that returns any duplicate values in an array of ints and it is telling me that 'not all code paths return a value'. Here is my code:
public static int? FindDuplicate(this int[] arrayToFindDuplicateIn)
{
int previousint = int.MaxValue;
arrayToFindDuplicateIn = arrayToFindDuplicateIn.OrderByDescending(x => x).ToArray();
foreach (int number in arrayToFindDuplicateIn)
{
if (number == previousint)
{
return number;
}
else
{
return null;
}
previousint = number;
}
}
I think what you want is to remove your else return null; and put the return null; outside your foreach. Otherwise it will only loop once everytime.
If the array is empty, no value is returned, so just return something at the end or check the input array with arrayToFindDuplicateIn.Any()
I'm supposed to create a method that takes an array and tells if the number is odd or even. I think I'm close to the answer but when I ran the code, it popped up with "Index is outside the bounds of the array". Is there a way to fix that?
private static string OddOrEven(int[] integerArray, string[] numAssign)
{
foreach (int i in integerArray)
{
if (integerArray[i] % 2==0)
{
numAssign[i] = " is even";
string returnValue = integerArray[i] + numAssign[i];
return returnValue;
}
else
{
numAssign[i] = " is odd";
string returnValue = integerArray[i] + numAssign[i];
return returnValue;
}
}
return "";
}
I'm still new to c# so any help is really appreciated.
Your mistake here is with how foreach works. I'll provide a different example to help you understand:
List<Person> people = GetPeople();
foreach (Person p in people)
{
Console.WriteLine(p.Name);
}
As you can see, the variable in the foreach actually receives each item, not its index. It's just that you have a list of int so it's not so obvious for you.
It seems like you want a regular for loop:
for(int i = 0; i < integerArray.Length; ++i)
{
if (integerArray[i] % 2==0)
{
numAssign[i] = " is even";
string returnValue = integerArray[i] + numAssign[i];
return returnValue;
}
else
{
numAssign[i] = " is odd";
string returnValue = integerArray[i] + numAssign[i];
return returnValue;
}
}
The next curious thing is your return returnValue; - the if statement can only ever enter one or the other, so it will always return a string for the first item only. It won't go on to the second, third, fourth, etc. item as it has already left the method before the loop has a chance to move on to the next value.
Speculation
I expect you want an array of results like this:
private static string[] OddOrEven(int[] integerArray)
{
string[] resultValues = new string[integerArray.Length];
for (int i = 0; i < integerArray.Length; ++i)
{
if (integerArray[i] % 2==0)
{
string numAssign = " is even";
resultValues[i] = integerArray[i] + numAssign;
}
else
{
string numAssign = " is odd";
resultValues[i] = integerArray[i] + numAssign;
}
}
return resultValues;
}
Note that I've removed the numAssign incoming array from the method parameters, and now just build it within the method itself.
This would produce a result like this.
This question already has answers here:
.NET compiler and "Not all code paths return a value"
(5 answers)
Closed 4 years ago.
The compiler is complaining that the following code snippet won't always return. I have inspected it and don't see an issue.
private int MyFunction(int b)
{
int result = -1;
while (result != 1)
{
result = MySmallFunction(out var x);
if (result == 1)
{
return x;
}
}
}
private int MySmallFunction(out int x)
{
x = 1;
return 1;
}
MySmallFunction does stuff and returns a code, 1 meaning success, and the rest is an error code.
If it returns 1, that means that the out int x has a value.
If the return value is not 1 (error code), then I want to retry.
If MySmallFunction never returns 1, the application should just be stuck in a loop forever. That shouldn't be a problem for the compiler.
I rewrote the function to this:
private int MyFunction()
{
int result = -1;
int x = int.MinValue;
while (result != 1)
{
result = MySmallFunction(out x);
}
return x;
}
private int MySmallFunction(out int x)
{
x = 1;
return 1;
}
Now x will only be returned if MySmallFunction returns a status code of 1.
In the case that your while loop doesn't trigger, there is not return instruction, you need a return at the bottom of your function outside the while loop.
As per the signature of the method MyFunction() it should return a value to the calling method in all conditions. but in your case, you are returning a value only if (result == 1) in all other case it is invalid, so you have to add a return at the end, which will return an integer. So you have to change something like this:
private int MyFunction(int b)
{
int result = -1;
while (result != 1)
{
result = MySmallFunction(out var x);
if (result == 1)
{
return x;
}
}
return 0;
}
I scripted the following recursion function to calculate all of the possible paths from a target node to a start node in a graph using adjacency matrix.
private Stack<string> TestCaseGeneration(int TargetStateIndex, double[,] adjacancy, Stack<string> TotalResults = null, Stack<string> CarrierStack = null, int StartStateIndex = 0)
{
Stack<string> Result = CarrierStack;
Result.Push(TargetStateIndex.ToString() + " - ");
if (TargetStateIndex == StartStateIndex)
{
TotalResults.Push(StackToSingleString(Result));
return TotalResults;
}
else
{
List<string> neighbours = ListNeighbourLeadingToTargetNode(TargetStateIndex, adjacancy, EventIndex);
int NumberOfNeighbours = neighbours.Count;
if (NumberOfNeighbours != 0)
{
for (int i = 0; i < NumberOfNeighbours; i++)
{
return TestCaseGeneration(int.Parse(neighbours[i].ToString()), adjacancy, TotalResults, Result, StartStateIndex);
}
}
}
else return null;
}
The issue is return int the for loop, how can I fix it?
If you don't want to return anything set the return null; before the last }
If you put the return null; in a if else statement the compiler knows not all code paths return a value!
EDIT
I see your problem now sorry.
You need to create a variable wich you return at the end.
In the if statement you can edit the variable.
If the variable is never edited the default value of the variable is returned!
The think your code will always return a value. I suggest you throw an exception just before the last } of the method: It will compile and you get a nice chance to see your code in action! If it throws the exception, you know when it was not going to return a value.
As it has been pointed out your else statement does nothing. Consider laying out your method in layman's terms:
method(){
if(something){
// do stuff
return value
}
else{
// do something else but,
// never do anything with this information
}
return null
}
This is basically what your method looks like when you break it down. The else statement does things, but those things are never used anywhere.
Suppose inside that else statement you call the recursive function which recursively calls 1000 more times. At the end of this loop it will return either null or some value back to the else statement.
That else statement then does nothing with the return value, then returns null.
That recursive call is basically useless unless it, too, is returned.
Consider trying:
private Stack<string> TestCaseGeneration(int TargetStateIndex, double[,] adjacancy, Stack<string> TotalResults = null, Stack<string> CarrierStack = null, int StartStateIndex = 0)
{
Stack<string> Result = CarrierStack;
Result.Push(TargetStateIndex.ToString() + " - ");
if (TargetStateIndex == StartStateIndex)
{
TotalResults.Push(StackToSingleString(Result));
return TotalResults;
}
else
{
int NumberOfNeighbours = ListNeighbourLeadingToTargetNode(TargetStateIndex, adjacancy, EventIndex).Count;
if (NumberOfNeighbours != 0)
{
for (int i = 0; i < NumberOfNeighbours; i++)
{
return TestCaseGeneration(i, adjacancy, TotalResults, Result, StartStateIndex);
}
}
}
return null;
}
Note that I added a return statement to the recursive call within the else statement.
I am currently taking a C# class and in the class we are looking to take our error handling out of our primary code and build all the error handling and data parsing for all integers in another class, however the problem is you can only return one variable.
How can i return both a "true/false" (bool) and the parsed data from one class to another.
Class1.cs (primary code)
int num1;
Class2 class2Object = new Class2();
public Class1()
{
//constructor
}
public void Num1Method()
{
string tempVal = "";
bool errorFlag; //bool = true/false
do
{
errorFlag = false; //no error & initialize
Console.Write("Enter Num1: ");
tempVal = Console.ReadLine();
class2Object.IntErrorCheckMethod(tempVal);
}//close do
while (errorFlag == true);
}//close Num1Method
Class2.cs (error and parse handling)
public bool IntErrorCheckMethod(string xTempVal)
{
int tempNum = 0;
bool errorFlag = false;
try
{
tempNum = int.Parse(xTempVal);
}
catch(FormatException)
{
errorFlag = true;
tempNum = 999;
}
return errorFlag;
}//close int error check
So Class2 will only return the true/false (if there is an error or not), how can I also return the good parsed data back to Class1 to be put into the "int num1" variable?
Our professor can only think to remove the bool and use a dummy value (like if the data has an error, set the value to 999 and return it, then do an if elseif to check if the value is 999 then return an error message, otherwise submit the data to the variable.
I think its better code to be able to use a bool for the error as 999 could POSSIBLY be good data that is entered by the user.
Any ideas are appreciated,
Thanks!
You can use out parameter just like TryParse methods in .NET. BTW
instead of your method you can use
int tempNum;
errorFlag = Int32.TryParse(string, out tempNum);
Or if you really want to use your own method for parsing:
public bool IntErrorCheckMethod(string xTempVal, out int tempNum)
{
tempNum = 0;
bool errorFlag = false;
try
{
tempNum = int.Parse(xTempVal);
}
catch(FormatException)
{
errorFlag = true;
tempNum = 999;
}
return errorFlag;
}
Usage:
int num1;
public void Num1Method()
{
string tempVal;
do
{
Console.Write("Enter Num1: ");
tempVal = Console.ReadLine();
}
while(class2Object.IntErrorCheckMethod(tempVal, out num1));
}
Also consider to do some refactoring to your method:
public bool TryParse(string s, out int result)
{
result = 0;
try
{
result = Int32.Parse(s);
return true; // parsing succeed
}
catch(FormatException)
{
return false; // parsing failed, you don't care of result value
}
}