Most elegant way to check to see if a NameValueCollection has value - c#

I have a simple line of code: lead.InternalCompany = nvCollection["ic"];
I want to set lead.InternalCompany to the value retrieved, but if nothing is there to a blank string ""
I've tried to use nvCollection["ic"].HasValue();
I know I could do something simple like this
string value = nvCollection["ic"];
if (value == null) // key doesn't exist
{
lead.InternalCompany = "";
}
I'd ideally like a ternary if statement to accomplish this

Use the null-coalescing operator
The ?? operator is called the null-coalescing operator and is used to
define a default value for nullable value types or reference types. It
returns the left-hand operand if the operand is not null; otherwise it
returns the right operand.
lead.InternalCompany = nvCollection["ic"] ?? string.Empty;

Related

C#, is this "if... else..." block equivalent to one line of code using null-coalescing operator

I'm curious if this block of code:
//value is an object, maybe null, maybe not
if (value == null)
item.PassageStimuliTitle = "";
else
item.PassageStimuliTitle = value.ToString().Trim();
is equivalent to this line:
item.PassageStimuliTitle = (string)(value ?? value.ToString().Trim());
I've used if... else... for a long time, but recently came across the null-coalescing operator in C#. I've used it to prevent null exception errors for params passed in method calls. I think using it in the example above is equivalent, and condenses the code from 4 lines to 1. Thanks for reading. Curious to hear feedback.
I'm expecting the two examples to be equivalent, but curious if there's something I'm missing.
No, the null-coalescing operator expression is not written correctly. a ?? b means "evaluate to b if a is null, otherwise evaluate to a". Therefore, your use of the null-coalescing operator will always produce a NullReferenceException if value is null - your code will try to evaluate value.ToString() when value is null.
Your use of ?? would translate to something like the following if statement, which I think you'd agree is quite non-sensical:
if (value == null) {
item.PassageStimuliTitle = (string)value.ToString().Trim();
} else {
item.PassageStimuliTitle = (string)value;
}
With certain assumptions, the if statement can be rewritten as:
item.PassageStimuliTitle = value?.ToString().Trim() ?? "";
This uses the null conditional operator ?.. If value is null, then the entire value?.ToString().Trim() expression is null, and hence the RHS of the ?? is evaluated. Otherwise, .ToString().Trim() is called on value.
item.PassageStimuliTitle = value != null ? value.ToString().Trim() : "";
From #Charles Mager comment:
item.PassageStimuliTitle = value?.ToString().Trim() ?? ""
Is a better and clearer one-liner.
You used ?? operator incorrectly.
In this example:
result = left_value ?? right_value;
?? operator returns left_value if it is NOT null.
If left_value is null, it returns right_value.
So, in your case, if variable value is of type object, it should be:
item.PassageStimuliTitle = (value ?? "").ToString().Trim();
Here is a successfully compiled code fiddle.

HasValue() or ?? operand when dealing with nullable types in LINQ-to-Entity,

I have had the following code to assign a value to nullable int variable:
ParentCommentId = lac.ParentCommentId ?? lac.ParentCommentId.Value,
However, with this code I was receiving the Nullable object must have a value error.
Then, I revised the code as follows:
ParentCommentId = lac.ParentCommentId.HasValue ? lac.ParentCommentId.Value : null,
And, now everything works fine. I wonder why ?? operand does not work in this case. Am I using it wrong? In what cases, ?? would be more suitable?
Nullable object must have a value is a runtime exception that occurs when you try to access .Value of a nullable with .HasValue false.
Your code:
ParentCommentId = lac.ParentCommentId ?? lac.ParentCommentId.Value
gets translated to:
if (lac.ParentCommentId.HasValue)
{
ParentCommentId = lac.ParentCommentId.Value;
}
else
{
ParentCommentId = lac.ParentCommentId.Value;
}
As you can see, both branches are doing the same and you would be accessing .Value even if HasValue is false (and will result in that exception).
The operator ?? is used to take the first not-null value. You can write
var value = value1 ?? value2 ?? value3;
The first of value1, value2, value3 that is not null will be assigned to value, if all are null then value will be set to null.
ParentCommentId = lac.ParentCommentId ?? lac.ParentCommentId.Value,
I wonder why ?? operand does not work in this case.
When you use the null-coalescing operator ?? it's shorthand for a short set of steps, the steps in a general sense do the following
Is lac.ParentCommentId something that can be null?
Yes -> Continue
No -> Give a compiler error saying you can't use the ?? operator on something that can't be null because it's the null-coalescing operator.
Is lac.ParentCommentId null?
Yes -> Continue
No -> Set the value of ParentCommentId to the value of lac.ParentCommentId, if they're the same type.
Set the value of ParentCommentId to the value of lac.ParentCommentId.Value, if they're the same type.
When you break down what the ?? operator does you can see that it runs into a problem right around step 2.
What you want is when lac.ParentCommentId has a value, to set ParentCommentId to lac.ParentCommentId.Value.
However, when you use the ?? that's not what you're doing. Instead it looks like you're saying 'When lac.ParentCommentId has a value, set ParentCommentId to lac.ParentCommentId'.
There is a way we can work around this, and it's actually pretty simple, because lac.ParentCommentId is already a nullable value we can simply use
ParentCommentId = lac.ParentCommentId ?? AlternativeValue
If we also consider that null is an acceptale value for ParentCommentId, we can actually simplify this even more for a more elegant solution and use:
ParentCommentId = lac.ParentCommentId
Edit: the following only applies to LINQ-to-Objects and not entity-framework. It remains as additional information on the ? null coelescing operator. Thanks to Ivan Stoev for pointing that out!
If the lac.ParentCommentId.Value is a null-able value you could instead use this:
ParentCommentId = lac?.ParentCommentId.Value ?? AlternativeValue,
What that does is it checks to see if ANY of lac ParentCommentId OR Value are null, and if ANY of them are null, use the alternative value.

Is there a conditional operator for setting a variable in C# to the value of another variable if the latter isn't null?

Something like the ternary operator (?:) or the null coalescing operator (??). It seems silly to me to take up two lines and be so wordy when the other operators exist.
EDIT:
Since it's requested, here's two possible examples of what I hope that I can find
var variable ?= mightBeNull;
or
var variable = mightBeNull != null ? mightBeNull
Really, it's either something that can be used to assign a value, if it's not null, to a variable or an If without an Else packaged nicely in an operator.
The ??= operator is coming to C# 8.
int? i = null; // i = null
i ??= 0; // i = 0
i ??= 1; // i = 0
// different ways of writing 'i ??= 0;':
i = i ?? 0;
if (i == null) i = 0;
So you want this?
if (other != null)
someVariable = other;
You could do the following, but I'd argue that the above is better due to clarity and possible side effects:
someVariable = other ?? someVariable;
The above might cause side effects if someVariable is a property and either the get or set can cause side effects; this shouldn't be important if your property follows the ordinary guidelines. Or, as Servy points out, even if it's a field, it could created different semantics in a multithreaded app. I should note that in the first example, you read other twice, which also has the potential for complexity to enter (though a smaller potential than the latter example).
I bet this is what you are looking for.
Let's say we have a function, myFunction that says whether the argument passed input is null or not. If input is null, it will return "Input is null!", else it will return "Input is not null".
This is the normal approach:
public String myFunction(string input) {
if (input == null)
return "Input is null!";
else
return "Input is not null";
}
And this is the other approach (What you are looking for):
public String myFunction(string input) {
return (input == null) ? "Input is null!" : "Input is not null";
}
It is called (?: conditional operator).
To assign a value to a variable only if it is not null, you would need to use an if. Neither the conditinal nor the null coalesce operators would do that.
if(somethingElse != null) something = somethingElse;
There is no specific operator in C# that does exactly this.
In Visual Studio 2015 C# there is a new operator called the Null-Conditional that does what you are asking. It is the ?. or ? operator.
int? length = customers?.Length; // null if customers is null
Customer first = customers?[0]; // null if customers is null
int? count = customers?[0]?.Orders?.Count(); // null if customers, the first customer, or Orders is null
Currently useable in previous versions of C# but not an operator but rather a one liner would be to use the ? : statement
?: operator
condition ? first_expression : second_expression;
AssingningTO = (someVar == null) ? null: someVar; // if null assign null ELSE assign someVar
AssingningTO = (someVar == null) ? String.Empth(): someVar; // if null assign empty string else someVar
Nullable types can represent all the values of an underlying type, and an additional null value.
http://msdn.microsoft.com/en-us/library/2cf62fcy.aspx

!= null vs. =null

See below code first please.
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
public struct MyStruct
{
public List<MyStructItem> Items;
}
public struct MyStructItem
{
public string Value;
}
static void Main(string[] args)
{
List<MyStruct> myList = new List<MyStruct>();
myList.Add(new MyStruct());
//(!) it haven't comipled.
if (myList[0].Items = null){Console.WriteLine("null!");}
//(!) but it have compiled.
if (myList[0].Items != null) { Console.WriteLine("not null!"); }
}
}
}
What is difference between !=null and =null in that case?
thanks.
You are using the assignment operator = instead of the equality operator ==.
Try:
//(!) it haven't comipled.
if (myList[0].Items == null){Console.WriteLine("null!");}
//(!) but it have compiled.
if (myList[0].Items != null) { Console.WriteLine("not null!"); }
The difference is one compiles and one doesn't :-)
C# Operators:
http://msdn.microsoft.com/en-us/library/6a71f45d(v=vs.80).aspx
= null is assignment. You should use == null
You assign the null value to myList[0].Items and tries to use it as bool in if statement. That is why code can not be compiled.
For example, this code compiles successfully:
bool b;
if (b = true)
{
...
}
Because you set true value to b and then check it in if statement.
=null you set the value to null
!= null you check if it is different from null
If you want to compare if it is equal to null, use == null instead of = null.
'=' is for assignment, not for comparing. Use '=='
if (myList[0].Items == null){Console.WriteLine("null!");}
First off, myList[0].Items = null will set the object to null. You probably mean myList[0].Items == null
And regarding the difference, == checked if something is equal. != checks if something is not equal.
For predefined value types, the equality operator (==) returns true if
the values of its operands are equal, false otherwise. For reference
types other than string, == returns true if its two operands refer to
the same object. For the string type, == compares the values of the
strings.
And
The assignment operator (=) stores the value of its right-hand operand
in the storage location, property, or indexer denoted by its left-hand
operand and returns the value as its result. The operands must be of
the same type (or the right-hand operand must be implicitly
convertible to the type of the left-hand operand).
Reference: http://msdn.microsoft.com/en-us/library/6a71f45d(v=vs.71).aspx
= is the assignment operator, you should use the equality operator ==
= null is an assignment. == null is a condition.
if (myList[0].Items != null)
is a negative comparison. It checks if myList[0].Items is not equal to null.
if (myList[0].Items = null)
is an assignment. It would normally assign null to myList[0].Items and return true (in languages like C++), however, in C#, this won't compile (because of this common error).

Shortest way to check for null and assign another value if not

I am pulling varchar values out of a DB and want to set the string I am assigning them to as "" if they are null. I'm currently doing it like this:
if (string.IsNullOrEmpty(planRec.approved_by) == true)
this.approved_by = "";
else
this.approved_by = planRec.approved_by.toString();
There seems like there should be a way to do this in a single line something like:
this.approved_by = "" || planRec.approved_by.toString();
However I can't find an optimal way to do this. Is there a better way or is what I have the best way to do it?
Try this:
this.approved_by = IsNullOrEmpty(planRec.approved_by) ? "" : planRec.approved_by.toString();
You can also use the null-coalescing operator as other have said - since no one has given an example that works with your code here is one:
this.approved_by = planRec.approved_by ?? planRec.approved_by.toString();
But this example only works since a possible value for this.approved_by is the same as one of the potential values that you wish to set it to. For all other cases you will need to use the conditional operator as I showed in my first example.
Starting with C# 8.0, you can use the ??= operator to replace the code of the form
if (variable is null)
{
variable = expression;
}
with the following code:
variable ??= expression;
More information is here
You are looking for the C# coalesce operator: ??. This operator takes a left and right argument. If the left hand side of the operator is null or a nullable with no value it will return the right argument. Otherwise it will return the left.
var x = somePossiblyNullValue ?? valueIfNull;
The coalesce operator (??) is what you want, I believe.
My guess is the best you can come up with is
this.approved_by = IsNullOrEmpty(planRec.approved_by) ? string.Empty
: planRec.approved_by.ToString();
Of course since you're hinting at the fact that approved_by is an object (which cannot equal ""), this would be rewritten as
this.approved_by = (planRec.approved_by ?? string.Empty).ToString();
With C#6 there is a slightly shorter way for the case where planRec.approved_by is not a string:
this.approved_by = planRec.approved_by?.ToString() ?? "";
Use the C# coalesce operator: ??
// if Value is not null, newValue = Value else if Value is null newValue is YournullValue
var newValue = Value ?? YourNullReplacement;
To extend #Dave's answer...if planRec.approved_by is already a string
this.approved_by = planRec.approved_by ?? "";
The accepted answer was correct in time, when it was given.
For people still finding this question:
Today you can use the ??= Operator.
e.g:
private string _test = null;
private void InitIfNull(){
_test ??= "Init";
}
To assign a non-empty variable without repeating the actual variable name (and without assigning anything if variable is null!), you can use a little helper method with a Action parameter:
public static void CallIfNonEmpty(string value, Action<string> action)
{
if (!string.IsNullOrEmpty(value))
action(value);
}
And then just use it:
CallIfNonEmpty(this.approved_by, (s) => planRec.approved_by = s);
You can also do it in your query, for instance in sql server, google ISNULL and CASE built-in functions.
I use extention method SelfChk
static class MyExt {
//Self Check
public static void SC(this string you,ref string me)
{
me = me ?? you;
}
}
Then use like
string a = null;
"A".SC(ref a);

Categories

Resources