Multiple component references in an if/then logic statements in Unity? - c#

How do you make multiple component references in a single if/then logic statements in Unity? I thought it would look something like this:
if(other.GetComponent<Component1>() != null || (GetComponent2>() != null)
{
//Run code
}
Such code returns this error:
error CS1026: ) expected

You are missing a get for the second component and a close )
if(other.GetComponent<Component1>() != null || other.GetComponent<Component2>() != null)
{
//Run code
}
With out knowing more, this is a start

Related

Dereference of a possible null reference C#

I have a C# method which throws the following warning on line await _socketClient.Start();:
CS8602: Dereference of a possibly null reference.
Method:
public async Task Connect()
{
if ((_socketClient == null) || (_socketClient != null && _socketClient.IsRunning))
return;
await _socketClient.Start();
}
I am not able to understand why the compiler is giving that warning even though I have made an explicit null check the line above it and returning back to the caller method?
Interestingly, if I simplify the method to do a plain simple null reference check, the warning goes away.
Modified Method (No warning):
public async Task Connect()
{
if (_socketClient == null)
return;
await _socketClient.Start();
}
However, I need the additional check as well and not sure what is the mistake I am doing over there for the warning to pop up.
Environment:
.Net 6.0 aspnet core application
Visual Studio 2022 IDE
Visual Studio only throws CS8602 when it detects the presence of "maybe-null".
Looks like you have it pretty much narrowed down, does refactoring it like below help at all?
public async Task Connect()
{
if ( _socketClient == null ) {
return;
} else if ( _socketClient.IsRunning ) {
return;
} else {
await _socketClient.Start();
}
}
The problem is that after || you are checking for null again, which makes the compiler "thinks" that _socketClient could be null when first check is false even though it is _socketClient == null
If it is written as follows, it does not warn about the nullability
public async Task Connect()
{
if (_socketClient is null || _socketClient.IsRunning)
return;
await _socketClient.Start();
}

SonarQube complaining to Change this condition so that it does not always evaluate to "true"

I am facing this issue in line number 2 while resolving sonarqube issue please suggest alternative to resolve it.
Exception exe = Server.GetLastError();
if (exe != null) {
Exception errorInfo = exe.GetBaseException();
var error = errorInfo as HttpException;
if (error != null)
isNotFound = error.GetHttpCode() == (int) System.Net.HttpStatusCode.NotFound;
}
The image you attached in your comment helped a lot.
There is a line that contains NLogManager.Error(... + exe.StackTrace); if it is executed correctly, then exe is not null, hence the if statement is redundant.
The analyzer does not raise issue on exe.StackTrace because at this point it is not sure if exe could be null or not (there is no check before).
I would recommend moving the line with NLogManager inside the if statement.

Why does the else statement not get executed if one of the bool parameters for if is null?

I have this code snippet here:
public void ReDrawParallelLines(string lineName, string viewType)
{
var referenceLineOne = GetLineParams(viewType + ReferenceEnum.One.ToString() + linename);
var referenceLineTwo = GetLineParams(viewType + ReferenceEnum.Two.ToString() + linename);
if (lineName == referenceLineOne.lineParams.lineName)
{
//Do certain action with referencelineone
}
else if (lineName == referenceLineTwo.lineParams.lineName)
{
//Do same action but with referencelinetwo
}
}
I noticed that if referenceLineOne is null but I have referenceLineTwo, the else statement never gets executed. I'm not sure why? Doesn't it work such that if the bool fails the if then continue to the else and it should pass for the else. It just skips the inside if statement and the else condition entirely because the referenceLineOne is null. Why and how can I correct this check?
Basically, I am passing a line name and I want to check to see if it's equal to one of two lines I get from the GetLineParams function.
Since referenceLineOne is null, you will get an exception, which is why it bypasses the else if and jumps somewhere else.
You should do null checking like this
if (referenceLineOne != null && lineName == referenceLineOne.lineParams.lineName)
{
//Do certain action with referencelineone
}
or this if you use c#6
if (lineName == referenceLineOne?.lineParams.lineName)
{
//Do certain action with referencelineone
}

Compiling error Nullreference

I'm compiling a program which was originally build in Visual C# 2005. I'am using visual C# 2010. And I keep getting "NullReference Execption was unhandled" errors when running the program on the following functions:
The error occurs on the line with DataBuffer. DataBuffer is an private string set to null on initialisation.
if (DataBuffer.Contains(ok))
{
okFound = true;
}
and
string temp = getLine(DataBuffer.Substring(mylocation));
if (!checkTypeFound())
{
if (temp != null)
{
parseDeviceType(temp);
}
checkTypeFound();
}
When I check what the value of DataBuffer is in the code above (when I get the error) this is not null. It actually contains the data I expect.
DataBuffer information is loaded in this function:
private void ser1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
while (ser1.BytesToRead > 0)
{
string data = ser1.ReadExisting();
DataBuffer += data;
}
}
The serial port is opened somewhere else in the code. There have been no changes to the code only the compiler is different. What line should I add, and where to solve this error? Note, I can prevent this error from happening using an if and try-catch statement. But this is not what I'm looking for, I need this code to work.
This application has not been changed in any way other than the compiler.
You should check if DataBuffer is null before you call its methods.
if (DataBuffer != null && DataBuffer.Contains(ok))
{
okFound = true;
}
// or simpler:
okFound = (DataBuffer != null && DataBuffer.Contains(ok));
and your second code snipped should check for null as well.
string temp = String.Empty;
if (DataBuffer != null)
temp = getLine(DataBuffer.Substring(mylocation));
if (!checkTypeFound())
{
if (!String.IsNullOrEmpty(temp))
parseDeviceType(temp);
checkTypeFound();
}
Try using the following:
if (DataBuffer != null && DataBuffer.Contains(ok))
{
okFound = true;
}
You should set the value of DataBuffer to something other than null in your constructor. If you can't do that then you may set it to string.Empty instead of null to avoid null exception. But it always better to check for null before initiating an instance method on object.

Refactoring exceptions for workflow

I am currently refactoring an application which uses exceptions for logic flow. The code is difficult to read and maintain and makes a S.O.L.I.D fanboy like myself cry when reading it (not to mention the longest catch block I've ever seen in my career).
My question is what pattern(s) could you use to make it easier to maintain or how would you go about refactoring?
public void CallExternalServices(ICriteria criteria)
{
try
{
someResult = ExternalService1.SomeMethod(criteria);
}
catch (Service1Exception service1Exception)
{
if (criteria.SomeValue == "1")
{
if (service1Exception.InnerException != null
&& service1Exception.InnerException.InnerException != null
&& service1Exception.InnerException.InnerException is TargetSystemException)
{
TargetSystemException targetSystemException = (TargetSystemException)service1Exception.InnerException.InnerException;
if (targetSystemException.ErrorStatus.IsServiceDownForMaintenance())
{
// Call internal method to perform some action
SendNotification("Service down for maintenance.")
}
}
}
else if (criteria.SomeValue == "2")
{
if (service1Exception.InnerException != null
&& service1Exception.InnerException.InnerException != null
&& service1Exception.InnerException.InnerException is TargetSystemException)
{
TargetSystemException tx = (TargetSystemException)service1Exception.InnerException.InnerException;
if (targetSystemException.ErrorStatus.IsBusy())
{
// Call to some internal method to perform an action
SendDifferentNotification()
criteria.SetSomeFlagToBe = true;
try
{
someResult = ExternalService2.SomeOtherMethod(criteria);
}
catch (Service2Exception service2Exception)
{
if (service2Exception.InnerException != null
&& service2Exception.InnerException.InnerException != null
&& service2Exception.InnerException.InnerException is TargetSystemException)
{
TargetSystemException tx = (TargetSystemException)service1Exception.InnerException.InnerException;
if (targetSystemException.ErrorStatus.HasNumberOfDailyTransactionsBeenExceeded())
{
// Call internal method to perform some action
SendNotification("Number of daily transactions exceeded.")
}
}
else if (service2Exception.InnerException != null
&& service2Exception.InnerException.InnerException != null
&& service2Exception.InnerException.InnerException is FaultException)
{
FaultException faultException = service2Exception.InnerException.InnerException as FaultException;
if (faultException.Detail != null
&& faultException.Detail.FaultMessage.Equals("SomeValueToCheckAgainst", StringComparison.OrdinalIgnoreCase))
{
return someResult;
}
else
{
throw service2Exception;
}
}
else
{
throw service2Exception;
}
}
if (someResult != null)
{
// perform another action
SomeActionInvoker.ExecuteAcitonAgainst(someResult);
}
}
}
else if (service1Exception.InnerException != null
&& service1Exception.InnerException.InnerException != null
&& service1Exception.InnerException.InnerException is FaultException)
{
FaultException faultException = service1Exception.InnerException.InnerException as FaultException;
if (faultException.Detail != null
&& faultException.Detail.FaultMessage.Equals("SomeOtherValueToCheckAgainst", StringComparison.OrdinalIgnoreCase))
{
return someResult;
}
else
{
throw service1Exception;
}
}
else
{
throw service1Exception;
}
}
}
}
All in all I think you would be helped by breaking up some stuff into some helper methods. For example, you could extract your checks that look like this
if (<exception-instance>.InnerException != null &&
<exception-instance>.InnerException.InnerException != null &&
<exception-instance>.InnerException.InnerException is <exception-type>)
Into a boolean method; you call code like this at least 3 times by my cursory glance.
Also, I would recommend extracting that second top-level case into an error-handling method; and perhaps its nested if statements.
Check out Working Effectively with Legacy Code by Michael Feathers, particularly Chapter 22 (I Need to Change a Monster Method and I Can't Write Tests for It). There are a lot of great techniques in there for situations like yours. Personally, in cases like this I usually end up extracting methods from sections of the longer methods, and getting rid of local variables that are used throughout the method; these are almost always trouble.
Start by refactoring the method into multiple methods. You've got waaaaaay too many levels of indentation going on.
After that, consider if some of the new methods could be extracted into other objects, and use an IoC-style approach rather than a procedural one.
That's kind of a high level answer, but I'm tired and don't have the energy to actually rework the code myself :)

Categories