I have a property in a class
public class User {
public string FiscalCode {get; set;}
}
And i want test the property fiscal code with two condition.
The test is ok if fiscalcode is null or fiscalcode is verified by a method
public bool FiscalCodeIsCorrect(string fiscalcode)
{
....
}
How can i test in a single line with shouldly if one of the two conditions is verified ?
I want use this condition in a test project so the line of code could be
user.FiscalCode.ShouldBeOneOf()
But i can't because null and string are two different types.
ShouldBeOneOf can not deal an function, so I think the simple way is using ShouldBeTrue
(FiscalCode == null || FiscalClodeIsCorrect(FiscalCode)).ShouldBeTrue();
I think you can just use basic ||:
if ( FiscalCode == null || FiscalCodeIsCorrect(FiscalCode) )
{
//something
}
|| is logical OR operator. This evaluates to true in case at least one of the operands evaluates to true. Also, note that it does short-circuiting which means if the FiscalCode is null it will not call FiscalCodeIsCorrect at all.
what #Martin Zikmund sugessted is right too but in your case both Null and FiscalCodeIsCorrect should be ok. So putting the null validation logic in FiscalCodeIsCorrect should be a better solution, then you wont have to validate if null every time.
so here is what i mean
public bool FiscalCodeIsCorrect(string fiscalcode)
{
if (fiscalcode == null)
return true;
//....You code here
}
now you only have to chack
if (FiscalCodeIsCorrect(FiscalCode) )
{
//something
}
Related
C# provides conditional operator (?:) that returns one of two values depending on the value of a Boolean expression. eg
condition ? first_expression : second_expression;
My question is can we use the same syntax to call a method when condition is true? and when condition is false then do nothing
public void Work(int? val)
{
var list = new List<int>();
//ofcourse line below doesn't work
//but is it possible to call method when condition is true and else do nothing
val.HasValue? list.Add(val.value) : else do nothing
}
the ?: has also been referred to as the ternary operator in the past. Ternary, for three. if this, then do this, else do this.
You have two expressions. If this, do this. This is exactly the point of an if statement. You are trying to fit your case into a construct that it isn't designed for. Don't do this.
Use the correct operation for the job:
if(val.HasValue)
{
list.Add(val.value)
}
The C# conditional operator is used to return a different value depending on the evaluation of a condition. It is not meant to be used to to be used the way you are trying to in your question. It should like be used this :
int test = i > 3 ? 0 : 1;
test will then equal 0 if i is less than (or equal to) 3, or test will equal 1 if 3 is greater than 3.
To do what you want you will have to use a regular if statement (which you can still write in one line by the way) :
if (val.HasValue) list.Add(val.value);
The conditional/ternary operator is supposed to return a value and that very specific value must be assigned back to somewhere.
So, in that case you can do that, yes. But, it would lead to bad design.
In a regular case, one would do this:
int x = (a > b) ? a : b;
Now, lets assume AddToList() is your desired method when the condition renders to true and DoRest() is the method you want to invoke if the condition turns out to false.
In the aforementioned case, you'd end up doing something like this:
int result = val.HasValue? AddToList(val.value) : DoRest();
Now you have to rely on result for finding out which one has been called (if you ever need that) and it's not very expressive and doesn't point to proper code design.
If you get a tad more adventurous you'd end up with :
var actionToInvoke = val.HasValue ? (Action)AddToList: (Action)DoRest;
actionToInvoke();
In any case, none of these lead to very readable code.
So, sticking with a simple if(val.HasValue) would be the simplest way to go here.
The way null conditional operator works is you have to return a value for the variable you are assigning it to. So if you would like a string value or something else other than void you can call the method with out any problem. But to call a void method you can use a delegate.
delegate void DelMethod();
void Method() { }
void MethodTwo() { }
private void MyMethod()
{
DelMethod x;
x = condition == true ? (DelMethod)Method : (DelMethod)MethodTwo;
}
I have a slight problem when working with c# and using IF statments with multiple conditions.
This is the most common occurance.
private void SomeFunction(string SomeString)
{
if(SomeString != null && SomeString.Trim() != "")
{
}
}
In some languages like javascript if the first argument fails (SomeString != null) the second check wont be made. C# seems to check both arguments even if the first one fails and then the second one will throw an exception since you cannot use .Trim() on a null value.
Right now I am going over this by nesting my ifs which is messy work. Like this:
private void SomeFunction(string SomeString)
{
if(SomeString != null)
{
if(SomeString.Trim() != "")
{
.....
}
}
}
Does anybody have any suggestions or best practices on a better way to solve this?
C# seems to check both arguments even if the first one fails
That's not true, see && Operator (C# Reference) in MSDN.
Your assumption is totally wrong. When you use the conditional AND if the first condition is FALSE the second condition is never evaluated or executed. In the conditional OR if the first condition is TRUE the second one is never evaluated or executed.
In other words, if the compiler has enough info to determine the result of the expression it stops to consider the second part of the expression.
This is known as short-circuit evaluation.
It is a basic programming principle for C derived languages but also for every other major language.
There is a better way:
private void SomeFunction(string SomeString)
{
if (!string.IsNullOrWhiteSpace(SomeString))
{
// your code
}
}
if (!String.IsNullOrEmpty(SomeString))
{
}
if(!string.IsNullOrEmpty(SomeString))
similar to ProgramFOX prefer this if you insist on doing ".Trim()"
Considering the following code
public bool GetFalse()
{
return false;
}
public bool GetTrue()
{
return true;
}
How can I force this expression GetFalse() && GetTrue() to execute second Method?
Try with:
GetFalse() & GetTrue()
You can't because the logical AND operator short circuits. In the general case it is a good idea to avoid side effects from expressions like that, although there are perfectly valid uses (i.e., if( someObj != null && someObj.Value == whatever ). You could use the bitwise and operator (&) which does not short circuit, but again, I wouldn't do that.
You should split those two method calls into variables first and then perform the check if you need them both to execute.
bool first = SomeMethodCall();
bool second = SomeMethodThatMustExecute();
if( first && second )
{
// ...
}
Use the non-short circuiting version (also known as the bit-wise AND when not working with Boolean values):
GetFalse() & GetTrue();
This is an optimization issue. Since the first method called in the expression is false, the entire expression cannot be true, so the second method in the expression is not called. If it is necessary to call this for a side effect (bad practice to rely on a side effect, but YMMV), something like this should be used:
x = GetFalse();
y = GetTrue();
if (x && y) ...
Assuming that your actual functions perform some specific tasks and return a value indicating (for example) success or failure I would prefer to see this written as
bool fooResult = DoFoo();
bool barResult = DoFar();
And then you can use fooResult && barResult in your code.
Is there any difference between below two statements
if (null != obj)
and
if (obj != null)
If both treated same which will be preferable?
The first is a Yoda condition. Use it you should not.
The difference here is the code generated. The two will not generate the exact same code, but in practice this will have no bearing on the results or performance of the two statements.
However, if you create your own types, and override the inequality operator, and do a poor job, then it will matter.
Consider this:
public class TestClass
{
...
public static bool operator !=(TestClass left, TestClass right)
{
return !left.Equals(right);
}
}
In this case, if the first argument to the operator is null, ie. if (null != obj), then it will crash with a NullReferenceException.
So to summarize:
The code generated is different
The performance and end results should be the same
Except when you have broken code in the type involved
Now, the reason I think you're asking is that you've seen code from C, which typically had code like this:
if (null == obj)
Note that I switched to equality check here. The reason is that a frequent bug in programs written with old C compilers (these days they tend to catch this problem) would be to switch it around and forget one of the equal characters, ie. this:
if (obj = null)
This assigns null to the variable instead of comparing it. The best way to combat this bug, back then, would be to switch it around, since you can't assign anything to null, it's not a variable. ie. this would fail to compile:
if (null = obj)
No, but the second way is more common and more readable (and more logical in my opinion)
No, there is not. It's exactly the same.
The style null == obj is sometimes just used to prevent the common typo obj = null to not accidently assign null to a variable, but with != there's absolutely no reason to do so.
In .NET it won't actually compile for the typo obj = null.
So the compiler prevents you from accidently doing it.
The Yoda condition comes originally from other languages, where this compiler feature is missing.
They are exactly the same.
Some people prefer to put the null as the first part of the expression to avoid errors like this
if (obj = null) // should be obj == null
But of course this doesn't apply to the != operator, so in your example it's just a difference of style.
First type of statement came from C/C++, where was possible to pass not boolean values to condition verification. E.g. anything not 0 was true, and zero was false:
if (5) { } // true
if (0) { } // false
Sometimes it created problems if you forgot to type one '=' char:
if (x = 5) { } // this was true always and changed x value
if (x == 5) { } // this was true, if x was equal to 5
So, Yoda syntax was used, to receive compiler error in case one '=' was missed:
if (5 = x) { } // this was generating compiler error for absent-minded programmers
if (5 == x) { } // this was true, if x was equal to 5
C# allow only boolean value in conditions, So
if (x = 5) { } // this won't compile
if (x == 5) { } // this is true, if x was equal to 5
What about boolean types?
if (y = true) { }
if (y == true) { }
Well, this is useless code, because you can just write if (y).
Conclusion: Yoda syntax is gone with C/C++ and you do not need to use it anymore.
The use of the first form
if (blah == obj)
stems from the days when compilers would not catch if (obj = blah) i.e. unintentional assignment, unless compile warning level was set to maximum
What's the best way of writing robust code so that a variable can be checked for null and blank.
e.g.
string a;
if((a != null) && (a.Length() > 0))
{
//do some thing with a
}
For strings, there is
if (String.IsNullOrEmpty(a))
You can define an extension method to allow you to do this on many things:
static public bool IsNullOrEmpty<T>(this IEnumerable <T>input)
{
return input == null || input.Count() == 0;
}
It already exists as a static method on the System.String class for strings, as has been pointed out.
And if you are using .NET 4.0 you might want to take a look at String.IsNullOrWhiteSpace.
From version 2.0 you can use IsNullOrEmpty.
string a;
...
if (string.IsNullOrEmpty(a)) ...
if(string.IsNullOrEmpty(string name))
{
/// write ur code
}
for strings:
string a;
if(!String.IsNullOrEmpty(a))
{
//do something with a
}
for specific types you could create an extention method
note that i've used HasValue instead of IsNullorEmpty because 99% of the times you will have to use the !-operator if you use IsNullOrEmpty which I find quite unreadable
public static bool HasValue(this MyType value)
{
//do some testing to see if your specific type is considered filled
}
I find Apache Commons.Lang StringUtils (Java)'s naming a lot easier: isEmpty() checks for null or empty string, isBlank() checks for null, empty string, or whitespace-only. isNullOrEmpty might be more descriptive, but empty and null is, in most cases you use it, the same thing.