boolean on the script, is saying error that says "not all code path return a value" for the function C# Unity [duplicate] - c#

This question already has answers here:
C# compiler error: "not all code paths return a value"
(9 answers)
Closed 21 hours ago.
I am getting an error message That "not all code paths return a value" for this code.
public bool IsInteractable(Vector3Int position)
{
//getting the tile
TileBase tile = InteractableGround.GetTile(position);
//Checking the name of the tilemap
if (tile != null)
{
if (tile.name == "Interactable")
{
return true;
}
return false;
}
}
I think the issue might be with the string for the file name, but i have copy and paste the name of the tile.

It’s because when your if statement condition is not met your if block is skipped right? So the code inside your if statement is not executed.
You need to include a return false or similar after your if statement or in an else statement :)

This error means that there is one possibility where your code won't have a return statement.
Here, if your tile is null, you don't return anything, which is causing C# to throw this error.

Related

Getting "not all code paths return a value" for code that will never not return a value

The method I write doesn't return a value though I write every possible conditions to return a value.
What I understand is whenever the compiler sees the return keyword it'll stop, execute the program and return the value next to the return keyword. Even if it is in the loop it'll break the loop and return the value but it the compiler shows the "not all code paths return a value" error. And there's an else conditions for the other possible conditions and how comes the error show up.
So, how the return keyword actually work?
I am so confused.
using System;
public static class PhoneNumber
{
public static (bool IsNewYork, bool IsFake, string LocalNumber) Analyze(string phoneNumber)
{
bool flag = true;
string[] numSub = phoneNumber.Split("-");
while(flag)
{
if(numSub[0] == "212")
{
if(numSub[1] == "555")
{
return (true, true, numSub[2]);
}
else{return (true, false, numSub[2]);}
} // end of if condition
else{
if(numSub[1] == "555")
{
return (false, true, numSub[2]);
}
else{return (false, false, numSub[2]);}
} // end of the else condition
} // end of the loop
}
not all code paths return a value
The compiler is not "smart" enough to know that you will enter the while loop. So it sees the code path that doesn't enter the while loop as a possible code path without a return.
As-written the code structure doesn't make much sense, so it should probably be restructured to make the compiler happy, and be easier to read and maintain. You can also just a thrown exception after the while to get rid of the compilation error.

Check if element exists appium C#

I have made a number of unit tests and I'm running them using appium. When an error pops up I try and capture it by
if (PowerPointSession.FindElementByAccessibilityId("CreateErrorIcon").Displayed == true)
{
exception = "An error occured when creating Agenda/TOC";
ExceptionHandler(exception);
}
This works fine if I have an error and it finds an element called CreateErrorIcon. However if no error pops up it seems to get stuck at the beginning of the if statement as if it is checking for an element called CreateErrorIconto be displayed and for some reason it never gets out of the if statement if it doesn't find the element.
Has anyone got any ideas or can point me in the right direction on why this is happening?
This post answers your question.
Basically, FindElementByAccessibilityId waits until an element is found or a timeout occurs.
In C# the check would look something like:
private static bool IsElementPresent(WindowsDriver<AppiumWebElement> driver, Action findAction)
{
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.Zero);
try
{
findAction();
return true;
}
catch (Exception)
{
return false;
}
finally
{
driver.Manage().Timeouts().ImplicitlyWait(GuiTestRunner.Timeout);
}
}
and usage:
var isError = IsElementPresent(PowerPointSession,
() => PowerPointSession.FindElementByAccessibilityId("CreateErrorIcon"));
if (isError)
{
exception = "An error occured when creating Agenda/TOC";
ExceptionHandler(exception);
}

Why would a NullReferenceException get thrown because my method returns null? [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
As shown below I have a method in my class that returns null as expected when it does not successfully read a value. I assume that the object "test" would just be set to NULL but for some reason an error is getting thrown.
I don't understand why this would throw an error...
private string myNullFunction() { return null; }
private void myFunction()
{
object test = myNullFunction();
}
when this does not...
private void myFunction()
{
object test = null;
}
Your sample code does not actually throw an exception. The real issue is shown in the code snippet above the exception dialog: m_xml.Read is returning null, but you are trying to access the Value property.
Read function is returning null. That's why null reference exception is there.

How to fix unreachable code dedected warning

dbLinq XMlMappingSource.cs contains code:
public void ReadEmptyContent(XmlReader r, string name)
{
if (r.IsEmptyElement)
r.ReadStartElement(name, DbmlNamespace);
else
{
r.ReadStartElement(name, DbmlNamespace);
for (r.MoveToContent(); r.NodeType != XmlNodeType.EndElement; r.MoveToContent())
{
if (r.NamespaceURI != DbmlNamespace)
r.Skip();
throw UnexpectedItemError(r);
}
r.ReadEndElement();
}
}
This causes compile warning
Warning CS0162 Unreachable code detected
at line
for (r.MoveToContent(); r.NodeType != XmlNodeType.EndElement; r.MoveToContent())
( https://github.com/DbLinq/dblinq2007/blob/d7a05bb452b98fd24bca5693da01ecfecd4f3d40/src/DbLinq/Data/Linq/Mapping/XmlMappingSource.cs#L176 )
in third part of for clause r.MoveToContent()
It looks like normal node traversal code and third part of for is reached.
How to fix this ?
Using .NET 4
You never execute the increment step, because your first run through the loop always throws an exception.
As Rawling stated you are throwing the exception no matter what.
Try changing the loop to this:
for (r.MoveToContent(); r.NodeType != XmlNodeType.EndElement; r.MoveToContent())
{
if (r.NamespaceURI != DbmlNamespace)
r.Skip();
else
throw UnexpectedItemError(r);
}
This will fix your issue.

Check object null or not [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
I wanted to check if User exists or not in the database, and i take a User object and check if it is null or not.But the problem is in my code if user doen't exist in our database it returns following exception,
Object reference not set to an instance of an object.
I know this error happen when there is no such a user in our database.So.. i wanted to know if this user object( i want to return null or not) null or not.
My Part of Code
if(newsManager.GetUserUsingEmail(User.Email).Email != null) //If user doesn't exists this come the above mentioned exception
{
//User Exists
}
else
{
//User Doesn't exists
}
How to solve it ?
The null reference exception is probably due to you trying to access the Email property on the user returned from the GetUserUsingEmail method. You should test if the returned value is null first and only then try accessing properties on it.
var user = newsManager.GetUserUsingEmail(User.Email);
if (user != null)
{
// user exists
}
else
{
// user does not exist
}
if newsManager.GetUserUsingEmail(User.Email) returns null, then you will agree that attempting to invoke .Email should give you the Object reference not set to an instance of an object. error, right?
As suggested in the comments, if your condition is truly just checking to see if the user exists or not, then simply do this:
if(newsManager.GetUserUsingEmail(User.Email) != null) //If user doesn't exists this come the above mentioned exception
{
//User Exists
}
else
{
//User Doesn't exists
}
If, as your code suggests, your intent is really to enter the if block only if you have a valid Email value for a valid user, then you can do that like this instead:
var user = newsManager.GetUserUsingEmail(User.Email);
if(user != null && !string.IsNullOrEmpty(user.Email))
{
//User Exists and has a valid email
}
else
{
//User Doesn't exists or doesn't have a valid email.
}
You cannot get property from null. Check object != null instead:
if(newsManager.GetUserUsingEmail(User.Email) != null) //If user doesn't exists this come the above mentioned exception
{
//User Exists
}
else
{
//User Doesn't exists
}
In C# 6.0 you can use Safe Navigation Operator (?.):
if(newsManager.GetUserUsingEmail(User.Email)?.Email != null) //If user doesn't exists this come the above mentioned exception
{
//User Exists
}
else
{
//User Doesn't exists
}

Categories

Resources