Simple Code throws expected ; error - c#

I have created a simple Code using if else clause,it throws error like expected ";". But when I check the code everything seems correct. I am new to C# coding.
public string empstatus(string trmdate, string status)
{
if( trmdate!= NULL)
{
if(status = "RETIREE")
{
return "RT";
}
else retun "FT";
}
else return "TF";
}

This compiles:
public string empstatus(string trmdate, string status)
{
if( trmdate!= null)
{
if(status == "RETIREE")
{
return "RT";
}
else return "FT";
}
else
return "TF";
}
Mistakes:
retun instead of return
if(status = "RETIREE") instead of if(status == "RETIREE")
NULL instead of null

if(status = "RETIREE") should be if(status == "RETIREE")
Also consider checking status for Null.

Please read about c# operators - https://msdn.microsoft.com/en-us/library/6a71f45d.aspx
You should compare 2 objects by using '==' operator.
if (status == "RETIREE")

explicit equasion == in c# is used to test the value of variable, while equasion = is used for value assignment

Related

Refactorisation of an if Block

In the following code I have 2 if block.
A, The first return the error when the object is null.
B, the second will try to send the object and if it' fails then return and error. It should be executed only if not A, the object is not null.
private bool SendToERP(Foo foo, out string error)
{
error = "";
var ticketIn = TicketFromFoo(foo, out string err);
if(ticketIn == null)
{
error = err;
return false;
}
if ( !GenericERP_TicketSubmit(ticketIn, out err))
{
error = err;
return false;
}
return true;
}
The action after those condition are the same and I want to refactor on into a unique if block.
As I can't warp my head 2 condition and an and I wrote a simple truth table to help me. But it didn't help me mutch.
The && and || operators short-circuit. It is considered from left to right. That means:
1) If && evaluates its first operand as false, it does not evaluate its second operand.
2) If || evaluates its first operand as true, it does not evaluate its second operand.
In your case, if ticketIn is null, you don't want the TicketSubmit executed.
So, you can group 2 conditions by an OR. Like this.
var ticketIn = TicketFromFoo(foo, out string err);
if(ticketIn == null || !GenericERP_TicketSubmit(ticketIn, out err))
{
error = err;
return false;
}
return true;
In your question you can combine two IF as #Thierry V answer
if(ticketIn == null || !GenericERP_TicketSubmit(ticketIn, out err))
but We can use another angle to read the question. This function expects to return bool so we can only write in a statement instead of IF.
return !(ticketIn == null || !GenericERP_TicketSubmit(ticketIn, out err))
We can use another skill (De Morgan's laws) let ! into the statement, that
will reverse all logic, let the code more clear.
1.ticketIn == null will be ticketIn != null
2.|| will be &&
3.!GenericERP_TicketSubmit(ticketIn, out err) will be GenericERP_TicketSubmit(ticketIn, out err)
so we can get
return ticketIn != null && GenericERP_TicketSubmit(ticketIn, out err)
the code can use like.
private bool SendToERP(Foo foo, out string error)
{
error = "";
var ticketIn = TicketFromFoo(foo, out error);
return ticketIn != null && GenericERP_TicketSubmit(ticketIn, out error);
}
I'd suggest to look up at c# 7 with new Value Tuples. We could also refactor all code on this way:
private (bool result, string error) SendToERP(Foo foo)
{
var result = TryMakeTicketFromFoo(foo, out TicketIn ticketIn);
return result.isSuccess ? GenericERP_TicketSubmit(ticketIn) : result;
}
You need to refactor semantic of your other method also:
private (bool isSuccess, string error) GenericERP_TicketSubmit(TicketIn ticketIn)
{
throw new NotImplementedException();
}
private (bool isSuccess, string error) TryMakeTicketFromFoo(Foo foo, out TicketIn ticketIn)
{
throw new NotImplementedException();
}

Evaluating boolean expression in C#

I have written the code below to evaluate a boolean expression. The expression is coded in the form of objects.
It's one of those moments when I look at the code and think: I'm sure there's a better way to code that, using less boolean variables but can't see the right way to go. Any help? Unit tests have been written and are passing for a variety of inputs.
if (tree == null || !tree.IsActive || tree.FilterNodes == null)
{
return false;
}
var result = false;
foreach (var filter in tree.FilterNodes.Where(a => a.IsActive && a.ConditionNodes != null))
{
var tempBool = false;
foreach (var condition in filter.ConditionNodes.Where(a => a.IsActive))
{
if (!string.IsNullOrWhiteSpace(condition.FieldName) && values.ContainsKey(condition.FieldName))
{
var value = values[condition.FieldName];
if (filter.LogicalOperator == LogicalOperator.Or && ApplyCondition(condition.ConditionOperator, value, condition.FieldValue))
{
tempBool = true;
break;
}
else if (filter.LogicalOperator == LogicalOperator.And)
{
tempBool = ApplyCondition(condition.ConditionOperator, value, condition.FieldValue);
if (!tempBool)
{
break;
}
}
else
{
tempBool = false;
}
}
else if (!string.IsNullOrWhiteSpace(condition.FieldName) && filter.LogicalOperator == LogicalOperator.And)
{
tempBool = false;
}
}
result = tempBool;
if (!result)
{
break;
}
}
return result;
You could set tempBool = false first thing in the loop and leave out the else and last else if:
foreach (var condition in filter.ConditionNodes.Where(a => a.IsActive))
{
tempBool = false;
if (!string.IsNullOrWhiteSpace(condition.FieldName) && values.ContainsKey(condition.FieldName))
{
var value = values[condition.FieldName];
if (filter.LogicalOperator == LogicalOperator.Or && ApplyCondition(condition.ConditionOperator, value, condition.FieldValue))
{
tempBool = true;
break;
}
else if (filter.LogicalOperator == LogicalOperator.And)
{
tempBool = ApplyCondition(condition.ConditionOperator, value, condition.FieldValue);
if (!tempBool)
{
break;
}
}
}
}
EDIT
It gets even simpler:
foreach (var condition in filter.ConditionNodes.Where(a => a.IsActive))
{
tempBool = false;
if (!string.IsNullOrWhiteSpace(condition.FieldName) && values.ContainsKey(condition.FieldName))
{
var value = values[condition.FieldName];
tempBool == ApplyCondition(condition.ConditionOperator, value, condition.FieldValue);
if ((filter.LogicalOperator == LogicalOperator.And && !tempBool) || (filter.LogicalOperator == LogicalOperator.Or && tempBool))
{
break;
}
}
}
In the if you need ApplyCondition to be true and then set tempBool to true (also the result of ApplyCondition). In the else if you set tempBoolto the result of ApplyCondition. That means you can set tempBoolto the result of ApplyConditionin the first place. Now you just need to decide if you need to break.
Taking a more o-o approach, I think your operators need to be defined by classes that inherit from a base class. The base class would have an abstract Evaluate method that your operators implement. You can then use o-o polymorphism to evaluate your operators without worrying about the internal details. Effectively you have the beginnings of a simple interpreter.
A more formal way to code a boolean interpreter is considering a boolean expression as generated by a formal grammar and writing a parser and an interpreter for it. The interpreter could be implemented as an abstract syntax tree.
I made an open source library to achieve this, if you want you can take a look on GitHub.

checking filename

How can i check if filename contains some string? for example if "frody" contains "ro"?
I tried like that:
if (file_name.Contains("ro")== true)
and:
if (file_name.Contains("ro"))
Both are correct. The second is probably more favoured.
E.g., this returns true:
string s = "test-ro.doc";
Console.WriteLine(s.Contains("ro"));
if (s == null || s.Trim().Length == 0)
{
return false
}
else
{
return s.ToLower().Contains("ro");
}

Error when assigning a boolean value

I am getting an error while assigning a value.
My code is:
protected bool ValidateProfile()
{
bool blnFirstName = false;
bool blnLastName = false;
bool blnEMail = false;
//(error on line below: "The left-hand side of an assignment must be a variable, property or indexer")
ValidateProfile() = false;
if txtFName != ""
blnFName = true;
if txtLName != ""
blnLName = true;
if txtEMail != ""
blnEMail = true;
if (blnFName) && (blnLName) && (blnEMail))
ValidateProfile = true;
}
How do I assign a boolean value to ValidateProfile ?
Thanks
You want
return false;
In C#, we don't assign values to the function name in order to return a value.
If you want to set the return value at a different point in time from when you return from the method, then you should do something like this:
bool retVal; // Defaults to false
if (condition)
retVal = true;
if (otherCondition)
retVal = false;
if (thirdCondition)
retVal = true;
return retVal;
You can't assign a value to a function. You need return false;
As others have pointed out, in C# you use return instead of MyFunction = x. In this scenario, you can assign the result of your final check to a boolean and return it:
bool retVal = (blnFName) && (blnLName) && (blnEMail);
return retVal;
Alternatively, you could just skip the assignment altogether:
return (blnFName) && (blnLName) && (blnEMail);
EDIT: I noticed you are using hungarian notation, which implies that txtFName is a TextBox. Keep in mind that C# doesn't have default properties like VB. If it is a TextBox, it will never equal "", because it's not of type System.String. I'm guessing you actually wanting to evaluate txtFName.Text
Change that last line to:
return false;
Although it seems you're always returning false here. Is there an option to return true?
Just a side note besides all the returns...
You may want to change this:
if txtFName != ""
To check if the String.IsEmptyOrNull(txtFName.Text)
Or at least initialize your variables to either null or String.Empty.
Just an FYI though.
You want to return false
Alright, taking the code you posted:
protected bool ValidateProfile()
{
return !String.IsNullOrEmpty(txtFName) && !String.IsNullOrEmpty(txtLName) && !String.IsNullOrEmpty(txtEMail);
}
Or
protected bool ValidateProfile()
{
bool returnValue = true;
if(String.IsNullOrEmpty(txtFName))
{
returnValue=false;
}
else if(String.IsNullOrEmpty(txtLName))
{
returnValue = false;
}
else if(String.IsNullOrEmpty(txtEMail))
{
returnValue = false;
}
return returnValue;
}
Though you could just return false as soon as you find an invalid field.
Not a C# programmer, but can't you just write:
return (txtFName != "") && (txtLName != "") && (txtEMail != "");
for the body of the function?

Determine value of object in C#

What would be the best way to determine if an object equals number zero (0) or string.empty in C#?
EDIT: The object can equal any built-in System.Value type or reference type.
Source Code:
public void MyMethod(object input1, object input2)
{
bool result = false;
object compare = new object();
if(input != null && input2 != null)
{
if(input1 is IComparable && input2 is IComparable)
{
//do check for zero or string.empty
//if input1 equals to zero or string.empty
result = object.Equals(input2);
//if input1 not equals to zero or string.empty
result = object.Equals(input1) && object.Equals(input2); //yes not valid, but this is what I want to accomplish
}
}
}
Using Jonathan Holland code sample with a minor modification, here is the solution that worked:
static bool IsZeroOrEmpty(object o1)
{
bool Passed = false;
object ZeroValue = 0;
if(o1 != null)
{
if(o1.GetType().IsValueType)
{
Passed = (o1 as System.ValueType).Equals(Convert.ChangeType(ZeroValue, o1.GetType()))
}
else
{
if (o1.GetType() == typeof(String))
{
Passed = o1.Equals(String.Empty);
}
}
}
return Passed;
}
What's wrong with this?
public static bool IsZeroOrEmptyString(object obj)
{
if (obj == null)
return false;
else if (obj.Equals(0) || obj.Equals(""))
return true;
else
return false;
}
Michael, you need to provide a little bit more information here.
strings can be compared to null or string.Empty by using the method
string x = "Some String"
if( string.IsNullOrEmpty(string input) ) { ... }
int, decimals, doubles (and other numeric value-types) can be compared to 0 (zero) with a simple == test
int x = 0;
if(x == 0) { ... }
You can also have nullable value-types also by using the ? operator when you instantiate them. This allows you to set a value type as null.
int? x = null;
if( !x.HasValue ) { }
For any other object, a simple == null test will tell you if its null or not
object o = new object();
if( o != null ) { ... }
Hope that sheds some light on things.
Not quite sure the reasoning behind this, because .Equals is reference equality on reference types, and value equality on value types.
This seems to work, but I doubt its what you want:
static bool IsZeroOrEmpty(object o1)
{
if (o1 == null)
return false;
if (o1.GetType().IsValueType)
{
return (o1 as System.ValueType).Equals(0);
}
else
{
if (o1.GetType() == typeof(String))
{
return o1.Equals(String.Empty);
}
return o1.Equals(0);
}
}
Do you mean null or string.empty, if you're talking about strings?
if (String.IsNullOrEmpty(obj as string)) { ... do something }
Oisin
In the first case by testing if it is null. In the second case by testing if it is string.empty (you answered your own question).
I should add that an object can never be equal to 0. An object variable can have a null reference though (in reality that means the variable has the value of 0; there is no object in this case though)
obj => obj is int && (int)obj == 0 || obj is string && (string)obj == string.Empty

Categories

Resources