How to avoid Tostring exception if string is null? [duplicate] - c#

This question already has answers here:
How to do ToString for a possibly null object?
(12 answers)
Closed 4 years ago.
I want to convert the data row value to sring as follows.
userGuid = dr["user_guid"].ToString();
It may contains Guid or null(Not string empty). If it contains null i got the exception.
How can i overcome this..

I guess you are reading from data reader.
You will have to check if the value is null or DBNull and then you can call to string method.
string user_guid = dr["user_guid"] != DBNull.Value && dr["user_guid"] != null ? dr["user_guid"].ToString() : null ;
Hope this helps.

if (dr[user_guid"] != null) {
//whatever you want to do
} else {
//handle the null value in some way
}
Alternatively,
dr["user_guid"]?.ToString();
The ? is what's called a "null-safe navigator".

This might be useful, one of many ways
userGuid = dr["user_guid"]?.ToString()?? "Default Value";
Please do replace "Default Value" with whatever you feel is appropriate according to your application logic.

Maybe this:
userGuid = dr["user_guid"].ToString() ?? throw new Exception();

Related

c# dynamic variable with ?? and ? operator [duplicate]

This question already has answers here:
What does a double question mark do in C#? [duplicate]
(7 answers)
What does question mark and dot operator ?. mean in C# 6.0?
(3 answers)
Closed 2 years ago.
Sorry for asking a simple question,
I'm new to Azure Function HTTPtriggers with C#,
Anyone know what is the name = name?? data?.name; mean in c# ?
string name = req.Query["name"];
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
name = name ?? data?.name;
It essentially means
if name is not null
set name to name
else
if data is null
set name to null
else
set name to data.name
The second operator (?.) avoids a NullReferenceException by returning null instead of trying to use the access modifier. The first (??) returns the first operand if the value is not null, otherwise it returns the second.
Note that neither of these are specific to dynamic or Azure.
It could also have been written as
if ((name == null) && (data != null))
{
name = data.name;
}

C# nullable check optimization [duplicate]

This question already has answers here:
Deep null checking, is there a better way?
(16 answers)
Closed 5 years ago.
Can anyone tell me how do I optimize below code.
if (report != null &&
report.Breakdown != null &&
report.Breakdown.ContainsKey(reportName.ToString()) &&
report.Breakdown[reportName.ToString()].Result != null
)
As others have mentioned, you can use the ?. operator to combine some of your null checks. However, if you're after optimizing for performance, you should avoid the double dictionary lookup (ContainsKey and index access), going for a TryGetValue instead:
MyType match = null; // adjust type
if (report?.Breakdown?.TryGetValue(reportName.ToString(), out match) == true &&
match?.Result != null)
{
// ...
}
Ayman's answer is probably the best you can do for C# 6, for before that what you have there is pretty much the best you can do if all those objects are nullable.
The only way to optimize this further is to be checking if those objects are null before even calling the code, or better yet proofing your platform so this particular function shouldn't even be called in the first place if the values are null.
If you are just getting the value from from the dictionary however you can also simplify with the null coalescing operater '??'
Example:
MyDictionary['Key'] ?? "Default Value";
Thus if the Value at that entry is null you'll get the default instead.
So if this is just a fetch I'd just go
var foo =
report != null &&
report.Breakdown != null &&
report.Breakdown.ContainsKey(reportName.ToString()) ?
report.Breakdown[reportName.ToString()].Result ?? "Default" :
"Default";
But if you are actually doing things in the loop, then yeah you're pretty much at the best you can get there.
For C# 6 and newer, you can do it this way:
if (report?.Breakdown?.ContainsKey(reportName.ToString()) == true &&
report.Breakdown[reportName.ToString()].Result != null)
You can use null conditional operator but only on C# 6
if ( report?.Breakdown?.ContainsKey(reportName.ToString()) == true &&
report.Breakdown[reportName.ToString()].Result != null )
Can you try below? Also probably better to ship it to a method.
// unless report name is already a string
string reportNameString = reportName.ToString();
if ( report?.Breakdown?.ContainsKey(reportNameString) &&
report.Breakdown[reportNameString].Result != null )
{
// rest of the code
}

Is there a way to return null instead of throwing a NullReferenceException? [duplicate]

This question already has answers here:
C# elegant way to check if a property's property is null
(20 answers)
Closed 7 years ago.
I have the following C# problem.
Consider the function:
private String getStringFromNullabel()
{
var nullable = getClass(); // returns some object that could be null
if( nullable != null)
{
return nullable.Text;
}
return null;
}
This works but it is verbose and I would rather write something like:
private String getStringFromNullabel()
{
return NotThrowWrapper(getClass()).Text;
}
This will throw if getClass() returns null.
So I am looking for some syntax that is short enough that this stays a one-liner but rather returns null instead of throwing an exception.
Is there such a thing in C#?
Pre C#6
private String GetStringFromNullabel()
{
var nullable = getClass(); // returns some object that could be null
return nullable != null ? nullable .Text : null;
}
Post C# 6
private String GetStringFromNullabel()
{
return getClass()?.Text;
}
Note that you should follow the .NET naming conventions

hierarchical-data with possible null object [duplicate]

This question already has answers here:
How to check for null in nested references
(6 answers)
Closed 7 years ago.
I have a big hierarchical object and I want one propertie from this structure. The problem is, every level of that object could be null. (It's data from a structured XML)
I want something like this:
_data = record.RltdPties.DbtrAcct.Id.Item
if one of this sub object is null, the data should be also null. Is there a better way the validate my object instead of this:
if(record!=null && record.RltdPties != null && record.RltdPties.DbtrAcct != null && record.RltdPties.DbtrAcct.Id != null)
{
_data = record.RltdPties.DbtrAcct.Id.Item
}
I could make a try{} catch{} block, but that's not a good solution.
with c# 5.0
_data = record?.RltdPties?.DbtrAcct?.Id?.Item
I think a try-catch-block would be the absolute right solution here, because you have to check the whole tree down and it does not look like there are any possible branches in the path of objects. It may not be C#-like but sometimes EAFP (easier to ask forgivenes than permission) keeps it simple enough.
try
{
_data = record.RltdPties.DbtrAcct.Id.Item
}
catch NullReferenceException
{
// do whatever then to do
}
If you can use C# 6.0, you could use the null conditional operator. http://www.codeproject.com/Articles/850832/What-s-new-in-Csharp-Null-conditional-operators
In your case it would be _data = record?.RltdPties?.DbtrAcct?.Id?.Item

Best C# method for checking for a null string value [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to check if String is null
I need to be able to check for a null value, only, inside a string. The best method I am currently aware of is String.IsNullOrEmpty(), which does not fit what we are trying to do (string.empty values are allowed, nulls are not). Does anyone have any suggestions?
just compare your string to null
bool stringIsNull = mystring == null;
here's an extension method for you
public static class ExtensionMethods
{
public static bool IsNull(this string str)
{
return str == null;
}
}
You check the same way you check if any other variable is null:
if(variable == null)
{
//do stuff
}
If you want to skip null values, simply use != null:
if(str != null)
{
}
if (variable != null)
//do your action for not null
else
//variable is null

Categories

Resources