Can the below logical if conditions be simplified ?
I have wrote this code but some parts are overlapping so I thought to seek for some help to see whether it can be simplified...
I have actually three different fields but following the same patterns.
EDIT :
if (Row.ReceivableAmount_IsNull == true && Row.CustomerID == LastCustomerID)
{
if (LastReceivableAmount == null)
{
Row.PreviousReceivableAmount_IsNull = true;
}
else
{
Row.PreviousReceivableAmount = LastReceivableAmount.GetValueOrDefault();
}
}
else
{
Row.PreviousReceivableAmount = LastReceivableAmount.GetValueOrDefault();
LastReceivableAmount = Row.ReceivableAmount;
}
if (Row.SaleAmount_IsNull == true && Row.CustomerID == LastCustomerID)
{
if (LastSaleDate == null)
{
Row.PreviousSaleDate_IsNull = true;
}
else
{
Row.PreviousSaleDate = LastSaleDate.GetValueOrDefault();
}
}
else
{
if (LastSaleDate == null)
{
Row.PreviousSaleDate_IsNull = true;
}
else
{
Row.PreviousSaleDate = LastSaleDate.GetValueOrDefault();
}
LastSaleDate = Row.Date;
}
if (Row.PaymentAmount_IsNull == true && Row.CustomerID == LastCustomerID)
{
if (LastPaymentDate == null)
{
Row.PreviousPaymentDate_IsNull = true;
}
else
{
Row.PreviousPaymentDate = LastPaymentDate.GetValueOrDefault();
}
}
else
{
Row.PreviousPaymentDate = LastPaymentDate.GetValueOrDefault();
LastPaymentDate = Row.Date;
}
Yes, you only care about LastSaleDate in your outer if condition, so move everything else out.
Once you've moved it out, you can invert your original condition, reducing your if/else to just an if.
if (LastReceivableAmount == null)
{
Row.PreviousReceivableAmount_IsNull = true;
}
else
{
Row.PreviousReceivableAmount = LastReceivableAmount.GetValueOrDefault();
}
if (!Row.ReceivableAmount_IsNull || Row.CustomerID != LastCustomerID)
{
Row.PreviousReceivableAmount = LastReceivableAmount.GetValueOrDefault();
LastReceivableAmount = Row.ReceivableAmount;
}
if (LastSaleDate == null)
{
Row.PreviousSaleDate_IsNull = true;
}
else
{
Row.PreviousSaleDate = LastSaleDate.GetValueOrDefault();
}
if (!Row.SaleAmount_IsNull || Row.CustomerID != LastCustomerID)
{
LastSaleDate = Row.Date;
}
if (LastPaymentDate == null)
{
Row.PreviousPaymentDate_IsNull = true;
}
else
{
Row.PreviousPaymentDate = LastPaymentDate.GetValueOrDefault();
}
if (!Row.PaymentAmount_IsNull == true || Row.CustomerID != LastCustomerID)
{
Row.PreviousPaymentDate = LastPaymentDate.GetValueOrDefault();
LastPaymentDate = Row.Date;
}
Since both branches of the if are similar, except one statement, you could use the following approach:
if (LastSaleDate == null)
{
Row.PreviousSaleDate_IsNull = true;
}
else
{
Row.PreviousSaleDate = LastSaleDate.GetValueOrDefault();
}
if (!Row.SaleAmount_IsNull || Row.CustomerID != LastCustomerID)
{
LastSaleDate = Row.Date;
}
Related
Hi guys actually first I wanted to do this loop.
Process p = Process.GetProcessesByName("etcProgram.bin")[0];
foreach (System.Diagnostics.ProcessModule moz in p.Modules)
if (csh.Text == "csh" || bin.Text == "bin")
{
if (moz.FileName.IndexOf("csh") != -1)
{
csh.Text = moz.BaseAddress.ToString();
}
if (moz.FileName.IndexOf("bin") != -1)
{
bin.Text = moz.BaseAddress.ToString();
}
}
else
{
!!!!!! return to "if" until "if code" happens !!!!!!
}
But my poor code knowledge can't come through this problem. So I wrote nearly same thinh with timer. Then I wrote this code.
private void tmrActive_Tick(object sender, EventArgs e)
{
try
{
Process p = Process.GetProcessesByName("Wolfteam.bin")[0];
foreach (System.Diagnostics.ProcessModule moz in p.Modules)
if (csh.Text == "csh" || bin.Text == "bin")
{
if (moz.FileName.IndexOf("csh") != -1)
{
csh.Text = moz.BaseAddress.ToString();
}
if (moz.FileName.IndexOf("bin") != -1)
{
bin.Text = moz.BaseAddress.ToString();
}
}
else
{
tmrActive.Stop();
MessageBox.Show("It's stopped");
}
}
But I saw that MessageBox appears 5-6 times when I started this.And I dont know why. So I dont feel very safe about use this code.
1- Do you know what's the problem with that timer. Shouldn't this messagebox appear once?
2- Can you help me about the code without timer.Is there anyway to do it?
You mean something like...
foreach (System.Diagnostics.ProcessModule moz in p.Modules)
{
bool breakloop = false;
while (!breakloop)
{
if (csh.Text == "csh" || bin.Text == "bin")
{
if (moz.FileName.IndexOf("csh") != -1)
csh.Text = moz.BaseAddress.ToString();
if (moz.FileName.IndexOf("bin") != -1)
bin.Text = moz.BaseAddress.ToString();
breakloop = true;
}
}
}
You can simply use break statement in order to stop a loop.
foreach (System.Diagnostics.ProcessModule moz in p.Modules)
{
if (csh.Text == "csh" || bin.Text == "bin")
{
if (moz.FileName.IndexOf("csh") != -1)
{
csh.Text = moz.BaseAddress.ToString();
}
if (moz.FileName.IndexOf("bin") != -1)
{
bin.Text = moz.BaseAddress.ToString();
}
break;
}
}
Hope this helps.
You could use this whole code as a Recursive function with a Specific condition to stop the condition whenever you want like this
foreach (System.Diagnostics.ProcessModule moz in p.Modules) { looping () {
bool breakloop = false;
while (!breakloop)
{
if (csh.Text == "csh" || bin.Text == "bin")
{
if (moz.FileName.IndexOf("csh") != -1)
csh.Text = moz.BaseAddress.ToString();
if (moz.FileName.IndexOf("bin") != -1)
bin.Text = moz.BaseAddress.ToString();
breakloop = true;
looping();
}
}
What am I doing wrong here?
At the end of the function, I'm returning the result.
public bool isStipends()
{
try
{
bool result = true;
if (tbstipend.Text == "" || tbstipend.Text == "Required")
{
tbstipend.Text = "Required";
tbstipend.BackColor = Color.Red;
tbstipend.ForeColor = Color.White;
result = false;
}
else if (tbstipendperperiod.Text == "" || tbstipendperperiod.Text == "Required")
{
tbstipendperperiod.Text = "Required";
tbstipendperperiod.BackColor = Color.Red;
tbstipendperperiod.ForeColor = Color.White;
result = false;
}
else if (tbstipendsperinterval.Text == "" || tbstipendsperinterval.Text == "Required")
{
tbstipendsperinterval.Text = "Required";
tbstipendsperinterval.BackColor = Color.Red;
tbstipendsperinterval.ForeColor = Color.White;
result = false;
}
else if (tbstipendrate.Text == "" || tbstipendrate.Text == "Required")
{
tbstipendrate.Text = "Required";
tbstipendrate.BackColor = Color.Red;
tbstipendrate.ForeColor = Color.White;
result = false;
}
else
{
return result;
}
}
catch
{
return false;
}
}
In the code behind of the button, I call:
private void btnupdatestipends_Click(object sender, EventArgs e)
{
try
{
if (isStipends() == true)
{
MessageBox.Show("TEST");
}
}
catch { }
}
However, it gives me an error on the function itself.
Error 3 'AddressBookMaint.Form1.isStipends()': not all code paths return a value C:\Win\AddressBookMaint\AddressBookMaint\Form1.cs 5040 22 AddressBookMaint
Any suggestions?
Thank you.
Error 1
You are only returning if none of the if's are true since the `return` is in the last `else` clause.
Solution
Break out the `return` from the last `else` and place it in the `try` block *(or even outside of the try/catch and you will solve error 2 as well)*.
Error 2
You will only return if there are no exceptions since you have the `return` at the end of the `try` block and no `return` in the `catch` block.
Solution
Add a `return` in the `catch` block and the code will compile.
Here's a working version of your code
public bool isStipends()
{
bool result = true;
try
{
if (tbstipend.Text == "" || tbstipend.Text == "Required")
{
tbstipend.Text = "Required";
tbstipend.BackColor = Color.Red;
tbstipend.ForeColor = Color.White;
result = false;
}
else if (tbstipendperperiod.Text == "" || tbstipendperperiod.Text == "Required")
{
tbstipendperperiod.Text = "Required";
tbstipendperperiod.BackColor = Color.Red;
tbstipendperperiod.ForeColor = Color.White;
result = false;
}
else if (tbstipendsperinterval.Text == "" || tbstipendsperinterval.Text == "Required")
{
tbstipendsperinterval.Text = "Required";
tbstipendsperinterval.BackColor = Color.Red;
tbstipendsperinterval.ForeColor = Color.White;
result = false;
}
else if (tbstipendrate.Text == "" || tbstipendrate.Text == "Required")
{
tbstipendrate.Text = "Required";
tbstipendrate.BackColor = Color.Red;
tbstipendrate.ForeColor = Color.White;
result = false;
}
}
catch
{
result = false;
}
return result;
}
You either need to return something in your catch:
public bool Method() {
try {
return true;
}
catch {
return false;
}
}
Or just return a single value at the bottom:
public bool Method() {
bool result = false;
try {
...
result = true;
}
catch {}
return result;
}
replace your method isStipends by this on:
public bool isStipends()
{
try
{
bool result = true;
if (tbstipend.Text == "" || tbstipend.Text == "Required")
{
tbstipend.Text = "Required";
tbstipend.BackColor = Color.Red;
tbstipend.ForeColor = Color.White;
result = false;
}
else if (tbstipendperperiod.Text == "" || tbstipendperperiod.Text == "Required")
{
tbstipendperperiod.Text = "Required";
tbstipendperperiod.BackColor = Color.Red;
tbstipendperperiod.ForeColor = Color.White;
result = false;
}
else if (tbstipendsperinterval.Text == "" || tbstipendsperinterval.Text == "Required")
{
tbstipendsperinterval.Text = "Required";
tbstipendsperinterval.BackColor = Color.Red;
tbstipendsperinterval.ForeColor = Color.White;
result = false;
}
else if (tbstipendrate.Text == "" || tbstipendrate.Text == "Required")
{
tbstipendrate.Text = "Required";
tbstipendrate.BackColor = Color.Red;
tbstipendrate.ForeColor = Color.White;
result = false;
}
return result;
}
catch { }
}
Your code only specifies the return in the final else block. In all your other code paths, including the catch block, you haven't specified any return value. You can drop that final else block and add a return value at the end of your function, like this:
public bool isStipends()
{
bool result = true;
try
{
...
}
catch
{
result = false;
}
return result;
}
However, catching all exceptions like this is very bad practice, and you certainly don't need to do it inside every function. You should only catch the exceptions you can meaningfully handle and allow the rest to bubble up. Set a global unhandled exception if need be to gracefully bail out of your application.
See Best Practices for Exceptions
The error is telling you that there are ways that do not return any value, if there is a mistake your catch instruction will returns nothing.
returns some value in your instruction catch.
You are not returning anything anywhere in your code... except for your last else statement. To compile all paths should return a bool value for your method. You should return a value in every if or if else and else statement, and in your catch block.
This will work:
public bool isStipends()
{
try
{
bool result = true;
if (tbstipend.Text == "" || tbstipend.Text == "Required")
{
tbstipend.Text = "Required";
tbstipend.BackColor = Color.Red;
tbstipend.ForeColor = Color.White;
result = false;
}
else if (tbstipendperperiod.Text == "" || tbstipendperperiod.Text == "Required")
{
tbstipendperperiod.Text = "Required";
tbstipendperperiod.BackColor = Color.Red;
tbstipendperperiod.ForeColor = Color.White;
result = false;
}
else if (tbstipendsperinterval.Text == "" || tbstipendsperinterval.Text == "Required")
{
tbstipendsperinterval.Text = "Required";
tbstipendsperinterval.BackColor = Color.Red;
tbstipendsperinterval.ForeColor = Color.White;
result = false;
}
else if (tbstipendrate.Text == "" || tbstipendrate.Text == "Required")
{
tbstipendrate.Text = "Required";
tbstipendrate.BackColor = Color.Red;
tbstipendrate.ForeColor = Color.White;
result = false;
}
else
{
return result;
}
}
catch
{
return false;
}
return result;
}
This line of (C#) code
if (!currentLap.S1.HasValue)
is giving me
System.NullReferenceException: Object reference not set to an instance of an object.
provided I'm sure that currentLap variable is instantiated (because it's being used a few lines before and it is a local variable) and it has following property:
private double? _s1;
[DefaultValue(null)]
[JsonConverter(typeof(ShortDoubleConverter))]
public double? S1
{
get { return _s1; }
set { _s1 = value; }
}
how can it possibly throw NullReferenceException? Can it be something to do with optimization on Release mode?
Thanks,
Stevo
EDIT:
here is full method code.
public void Update(DriverData driverData)
{
LapInfo currentLap = this.CurrentLap;
if (currentLap != null &&
this.LastDriverData != null &&
driverData.TotalLaps != this.LastDriverData.TotalLaps &&
driverData.InPits &&
driverData.Speed < 10 &&
!this.LastDriverData.InPits)
{
currentLap.Escaped = true;
}
this.LastDriverData = driverData;
if ((currentLap == null || currentLap.Lap != driverData.LapNumber) &&
!this.Laps.TryGetValue(driverData.LapNumber, out currentLap))
{
currentLap = new LapInfo() { Lap = driverData.LapNumber, Parent = this, Class = driverData.Class };
this.Laps.Add(driverData.LapNumber, currentLap);
int lapsCount = 0, completedDriverLaps = 0, cleanLaps = 0;
this.TotalLaps = driverData.TotalLaps;
//if it's not the first lap
if (driverData.TotalLaps > 0)
{
//previous lap
if (this.CurrentLap == null || !this.CurrentLap.Escaped)
{
this.CompletedLaps++;
if (this.CurrentLap == null || !this.CurrentLap.MaxIncident.HasValue)
this.CleanLaps++;
}
}
foreach (DriverLapsInfo laps in this.Parent.LapsByVehicle.Values)
{
lapsCount += laps.TotalLaps;
completedDriverLaps += laps.CompletedLaps;
cleanLaps += laps.CleanLaps;
}
this.Parent.Parent.SetLapsCount(driverData, lapsCount, driverData.Class, completedDriverLaps, cleanLaps);
}
this.CurrentLap = currentLap;
//add incidents
if (driverData.Incidents != null)
{
foreach (IncidentScore incident in driverData.Incidents)
{
this.CurrentLap.MaxIncident = Math.Max(this.CurrentLap.MaxIncident ?? 0, incident.Strength);
this.CurrentLap.Incidents++;
this.Incidents++;
}
}
LapInfo previousLap = null;
if ((this.PreviousLap == null || this.PreviousLap.Lap != driverData.TotalLaps) &&
this.Laps.TryGetValue(driverData.TotalLaps, out previousLap))
{
this.PreviousLap = previousLap;
if (!this.PreviousLap.Date.HasValue)
{
this.PreviousLap.Date = DateTime.UtcNow;
}
}
if (currentLap.Position == 0)
currentLap.Position = driverData.Position;
if (driverData.CurrentS1 > 0)
{
**if (!currentLap.S1.HasValue)**
{
this.UpdateBestS1(driverData.BestS1);
this.Parent.Parent.UpdateBestS1(driverData.BestS1, driverData.UniqueName);
currentLap.UpdateS1(driverData.CurrentS1, driverData);
//reset the best split set at the finish line
if (this.PreviousLap != null && this.PreviousLap.SplitBest < 0)
this.PreviousLap.SplitBest = 0;
}
if (driverData.CurrentS2.HasValue && driverData.CurrentS1.HasValue && !currentLap.S2.HasValue)
{
double s2 = driverData.CurrentS2.Value - driverData.CurrentS1.Value;
this.UpdateBestS2(s2);
this.Parent.Parent.UpdateBestS2(s2, driverData.UniqueName);
currentLap.UpdateS2(s2, driverData);
}
}
if (this.PreviousLap != null)
{
if (driverData.LastLap > 0)
{
if (!this.PreviousLap.S3.HasValue && driverData.LastS2.HasValue)
{
double s3 = driverData.LastLap.Value - driverData.LastS2.Value;
this.UpdateBestS3(s3);
this.Parent.Parent.UpdateBestS3(s3, driverData.UniqueName);
this.PreviousLap.UpdateS3(s3, driverData);
}
if (!this.PreviousLap.LapTime.HasValue)
{
double? bestLap = this.Parent.Parent.BestLap;
this.PreviousLap.UpdateLapTime(driverData, 0);
this.Parent.Parent.UpdateBestLap(this.PreviousLap, driverData.BestLap, driverData);
this.UpdateBestLap(driverData.BestLap, this.PreviousLap);
this.PreviousLap.UpdateLapTime(driverData, bestLap);
}
}
else
{
if (this.PreviousLap.SplitBest.HasValue)
this.PreviousLap.UpdateBestSplit();
if (this.PreviousLap.SplitSelf.HasValue)
this.PreviousLap.UpdateSelfSplit();
}
}
if (driverData.InPits)
{
switch (driverData.Sector)
{
case Sectors.Sector1:
if (previousLap != null)
previousLap.InPits = true;
break;
case Sectors.Sector3:
currentLap.InPits = true;
break;
}
}
//lap to speed
if (currentLap.TopSpeed < driverData.Speed)
{
driverData.TopSpeedLap = driverData.Speed;
currentLap.UpdateTopSpeed(driverData.Speed);
}
else
driverData.TopSpeedLap = currentLap.TopSpeed;
//overall top speed
if (this.TopSpeed < driverData.Speed)
{
driverData.TopSpeed = driverData.Speed;
this.TopSpeed = driverData.Speed;
this.Parent.Parent.UpdateTopSpeed(this.TopSpeed, driverData);
}
else
driverData.TopSpeed = this.TopSpeed;
}
There is no way on earth the code can make it to that line and currentLap beeing null.
Or am I going crazy? :)
.HasValue will not throw if the nullable reference is null, but a.b.HasValue will if a is null.
I suspect that currentLap == null. I know you say you're sure that currentLap is not null, but I think that's the most likely explanation. Can you post more code?
Update:
Thanks for posting your code.
This doesn't throw:
void Main() {
var f = new Foo();
Console.WriteLine (f.S1);
Console.WriteLine (f.S1.HasValue);
}
class Foo {
private double? _s1 = null;
public double? S1 {
get { return _s1; }
set { _s1 = value; }
}
}
Could you try to create a minimal reproduction? (minimal code that exhibits the issue)
Maybe have a look at the previous line of code :) - debugger often highlights the next line after the one where the NullReferenceException was actually thrown.
For some reason I have error generating code for a wcf service using "Add service reference" wizard.
Custom tool warning: No endpoints compatible with version 1 of windows immersive project were found. C:\work\test_projects\CirMetro\Service References\SvcProxy\Reference.svcmap 1 1 CirMetro
Do you guys know how to fix it ?
My sample WCF service is braindead simple. Here is source code:
static void Main()
{
UiWcfSession.OnInitialize += ClientInitialize;
var baseAddresses = new Uri("net.tcp://localhost:9000/");
var host = new ServiceHost(typeof(UiWcfSession), baseAddresses);
var reliableSession = new ReliableSessionBindingElement { Ordered = true, InactivityTimeout = new TimeSpan(24, 20, 31, 23) };
var binding =
new CustomBinding(reliableSession, new TcpTransportBindingElement()) { ReceiveTimeout = TimeSpan.MaxValue };
host.AddServiceEndpoint(typeof(IClientFulfillmentPipeService), binding, "svc");
var metadataBehavior = new ServiceMetadataBehavior();
host.Description.Behaviors.Add(metadataBehavior);
var mexBinding = MetadataExchangeBindings.CreateMexTcpBinding();
host.AddServiceEndpoint(typeof(IMetadataExchange), mexBinding, "mex");
host.Open();
Thread.CurrentThread.Join();
}
private static void ClientInitialize(int uiprocessid, string key)
{
Debug.WriteLine("ClientInitialize");
}
I figured it out.
It's unfortunate that we have to decompile sources of Visual Studio to find out what works in Metro instead of referring to non-existent documentation :-)
In short I can't use ReliableSession.
If you want more details C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\PrivateAssemblies\Microsoft.VisualStudio.ServiceReference.Platforms.dll contains function which check what is supported.
private static bool IsBindingSupported(Binding binding)
{
if ((!(binding is BasicHttpBinding) && !(binding is CustomBinding)) && (!(binding is WSHttpBinding) && !(binding is NetTcpBinding)))
{
return false;
}
if (binding is WSHttpBinding)
{
if (((WSHttpBinding) binding).ReliableSession.Enabled)
{
return false;
}
if (((WSHttpBinding) binding).TransactionFlow)
{
return false;
}
if (((WSHttpBinding) binding).MessageEncoding != WSMessageEncoding.Text)
{
return false;
}
}
if (binding is NetTcpBinding)
{
if (((NetTcpBinding) binding).ReliableSession.Enabled)
{
return false;
}
if (((NetTcpBinding) binding).TransactionFlow)
{
return false;
}
}
foreach (BindingElement element in binding.CreateBindingElements())
{
if (element is TransportBindingElement)
{
if ((!(element is HttpTransportBindingElement) && (!(element is HttpsTransportBindingElement) || (element as HttpsTransportBindingElement).RequireClientCertificate)) && !(element is TcpTransportBindingElement))
{
return false;
}
}
else if (element is MessageEncodingBindingElement)
{
if (!(element is BinaryMessageEncodingBindingElement) || (((BinaryMessageEncodingBindingElement) element).MessageVersion != MessageVersion.Soap12WSAddressing10))
{
if (element is TextMessageEncodingBindingElement)
{
if ((((TextMessageEncodingBindingElement) element).MessageVersion != MessageVersion.Soap11) && (((TextMessageEncodingBindingElement) element).MessageVersion != MessageVersion.Soap12WSAddressing10))
{
return false;
}
}
else
{
return false;
}
}
}
else if (element is SecurityBindingElement)
{
if (!(element is TransportSecurityBindingElement))
{
return false;
}
TransportSecurityBindingElement element2 = (TransportSecurityBindingElement) element;
if (!ValidateUserNamePasswordSecurityBindingElement(element2))
{
if (((((element2.EndpointSupportingTokenParameters.Endorsing.Count == 1) && (element2.EndpointSupportingTokenParameters.Signed.Count == 0)) && ((element2.EndpointSupportingTokenParameters.SignedEncrypted.Count == 0) && (element2.EndpointSupportingTokenParameters.SignedEndorsing.Count == 0))) && ((element2.EndpointSupportingTokenParameters.Endorsing[0] is SecureConversationSecurityTokenParameters) && ((element2.MessageSecurityVersion == MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10) || (element2.MessageSecurityVersion == MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10)))) && ((element2.IncludeTimestamp && (element2.DefaultAlgorithmSuite == SecurityAlgorithmSuite.Default)) && (element2.SecurityHeaderLayout == SecurityHeaderLayout.Strict)))
{
SecureConversationSecurityTokenParameters parameters = (SecureConversationSecurityTokenParameters) element2.EndpointSupportingTokenParameters.Endorsing[0];
if (parameters.RequireDerivedKeys || !(parameters.BootstrapSecurityBindingElement is TransportSecurityBindingElement))
{
return false;
}
TransportSecurityBindingElement bootstrapSecurityBindingElement = (TransportSecurityBindingElement) parameters.BootstrapSecurityBindingElement;
if (!ValidateUserNamePasswordSecurityBindingElement(bootstrapSecurityBindingElement))
{
return false;
}
}
else
{
return false;
}
}
}
else if ((!(element is SslStreamSecurityBindingElement) || (element as SslStreamSecurityBindingElement).RequireClientCertificate) && !(element is WindowsStreamSecurityBindingElement))
{
if (!(element is TransactionFlowBindingElement))
{
return false;
}
if ((!(binding is WSHttpBinding) || ((WSHttpBinding) binding).TransactionFlow) && (!(binding is NetTcpBinding) || ((NetTcpBinding) binding).TransactionFlow))
{
return false;
}
}
}
return true;
}
I am getting unreachable code detected for the second if statement. Can you please let me know what went wrong?
private bool ValidateSettings()
{
if (chkDownload.Checked && String.IsNullOrEmpty(txtAppName.Text))
{
divAppDownloadError.Visible=true;
return false;
}
else
{
return true;
}
if (chkpplaORfmp.Checked && String.IsNullOrEmpty(txtfmpORppla.Text))
{
divXPAAPPDownloadError.Visible = true;
return false;
}
else
{
return true;
}
}
This is because the first if/else block will return either way - no code after that block will execute:
if(chkDownload.Checked && String.IsNullOrEmpty(txtAppName.Text))
{
// You either return here
divAppDownloadError.Visible=true;
return false;
}
else
{
// or here - after this statement how can anything
// else possible execute?
return true;
}
Perhaps you want to remove the else blocks and just return true at the end.
Looks like you want to return false if any of the settings are not as expected. Let:
condition1 = chkDownload.Checked && String.IsNullOrEmpty(txtAppName.Text)
condition2 = chkpplaORfmp.Checked && String.IsNullOrEmpty(txtfmpORppla.Text)
The way it is written, we have
(condition1, condition2) = (true, true) => return true
(condition1, condition2) = (true, false) => return true
(condition1, condition2) = (false, true) => return false
(condition1, condition2) = (false, false) => return false
What it looks like you want is:
(condition1, condition2) = (true, true) => return true
(condition1, condition2) = (true, false) => return false
(condition1, condition2) = (false, true) => return false
(condition1, condition2) = (false, false) => return false
Your code is the equivalent of this, since both the if and else contain return statements:
private bool ValidateSettings()
{
if(chkDownload.Checked && String.IsNullOrEmpty(txtAppName.Text))
{
divAppDownloadError.Visible=true;
return false;
}
return true;
}
Samuel Carrijo is right; I think what you mean to do is check if any invalidating conditions are held and, if so, return false. But to check them all you must not return true until the end:
private bool ValidateSettings()
{
if (chkDownload.Checked && String.IsNullOrEmpty(txtAppName.Text))
{
divAppDownloadError.Visible=true;
return false;
}
if (chkpplaORfmp.Checked && String.IsNullOrEmpty(txtfmpORppla.Text))
{
divXPAAPPDownloadError.Visible = true;
return false;
}
// if you've gotten this far, neither of the
// invalidating conditions above were held;
// so you're good!
return true;
}
private bool ValidateSettings()
{
if ((chkDownload.Checked && String.IsNullOrEmpty(txtAppName.Text))||
(chkpplaORfmp.Checked && String.IsNullOrEmpty(txtfmpORppla.Text)))
{
if (chkDownload.Checked)
divAppDownloadError.Visible=true;
else divXPAAPPDownloadError.Visible = true;
return false;
}
return true;
}
Code simplified
private bool ValidateSettings()
{
if (chkDownload.Checked && String.IsNullOrEmpty(txtAppName.Text) && chkpplaORfmp.Checked && String.IsNullOrEmpty(txtfmpORppla.Text))
{
divAppDownloadError.Visible = true;
divXPAAPPDownloadError.Visible = true;
return false;
}
if ((chkDownload.Checked && String.IsNullOrEmpty(txtAppName.Text)) || (chkpplaORfmp.Checked && String.IsNullOrEmpty(txtfmpORppla.Text)))
{
if (chkDownload.Checked && String.IsNullOrEmpty(txtAppName.Text))
{
divAppDownloadError.Visible = true;
divXPAAPPDownloadError.Visible = false;
}
else
{
divXPAAPPDownloadError.Visible = true;
divAppDownloadError.Visible = false;
}
return false;
} return true;
}
this is working