Is there a function in c# that can help to check if the statement is going to return error.
I am aware about try{} catch{} but we can't use it in condition checking. For example:
var opertionResult = SomeRestFunction.Trigger();
string ServerResponse = if(operationResult != null)
{
if(operationResult.Response != null)
{
operationResult.Response.ResponseText;
}
Else
{
"Null";
}
}
Else
{ "Null"; }
In the example above, I need to perform multiple checks to validate the operationResult object properties at multiple levels due to nested objects in it, to determine the final value I want to read and consume as server response value.
If we have some thing like IsError() function in Excel, we can simply try to read the final object property i.e. operationResult.Response.ResponseText; inside of that function and if any of the parent object is null and it has to throw an error it will return false and we can return the value from the else block as shown in the hypothetical example below:
var opertionResult = SomeRestFunction.Trigger();
string ServerResponse = IsError(operationResult.Response.ResponseText)? "Null": operationResult.Response.ResponseText;
So, do we have something like this in C#? Hope this makes sense?
If you're using c# 6 or newer version then you can use null-conditional & null-coalescing-operator operator like below.
Here you need to place ? to check if object is null or not. If object is null then it will not perform any further check and return null. And null-coalescing-operator (??) will be used to check if value is null then it will return value provided afer ??.
string ServerResponse = SomeRestFunction.Trigger()?.Response?.ResponseText ?? "Null";
Related
I'm just looping and appending my properties to a big string:
output.Append(property.GetValue(this).ToString()));
When app breaks in that moment property represent a ProductNumber which is a string, value of this is Product object which has value of ProductNumber = null, so I've tried something like this:
output.Append(property.GetValue(this)?.ToString()));
But anyway it breaks..
How could I improve this code to avoid breaking there?
Thanks
Cheers
It seems that output.Append complains on null values. There are 2 possible sources of pesky nulls here:
property.GetValue(this) returns null and thus ?. in ?.ToString() propagates null
ToString() itself returns null (hardly a case, but still possible)
We can solve both possibilities with ?? operator: let's return an empty string whatever the source of null is:
property.GetValue(this)?.ToString() ?? ""
Final code is
output.Append(property.GetValue(this)?.ToString() ?? "");
This code:
output.Append(property.GetValue(this)?.ToString()));
Is the same as:
object propValue = property.GetValue(this);
string propString = null;
if (propValue != null)
{
propString = propValue.ToString();
}
output.Append(propString); // propString can be null
This can be simplyfied like so:
string propString = property.GetValue(this)?.ToString(); // This performs a ToString if property.GetValue() is not null, otherwise propString will be null as well
output.Append(propValue); // propValue can be null
If you want to prevent calling Append with a null value you can do:
string propString = property.GetValue(this)?.ToString(); // This performs a ToString if property.GetValue() is not null, otherwise propString will be null as well
if (propString == null)
{
propString = string.Empty;
}
output.Append(propValue); // propString is not null
This can be simplified with the null-coalescing operator:
string propString = property.GetValue(this)?.ToString() ?? string.Empty
output.Append(propValue); // propString is not null
I'm trying to assign a value to a string variable when making a change to a datagridview field. Unfortunately if it's blank, it crashes with a NullReferenceException even if I try to check if it's null. I also don't know of a more efficient way to write this.
string change = "";
if (dgGroups[cid, rid].Value.ToString() != null) //gets null reference exception if row/column is blank.
{
change = dgGroups[cid, rid].Value.ToString();
}
Your check should be like this. You are trying to call null.ToString() which is not valid and it will throw NullReferenceException .
string change = "";
if (dgGroups[cid, rid].Value != null)
{
change = dgGroups[cid, rid].Value.ToString();
}
If you are using C# 6.0 you can write
string change = dgGroups[cid, rid].Value?.ToString();//this will return null if Value is null
You can use the ?? operator:
change = (dgGroups[cid, rid].Value ?? defaultValue).ToString();
I am instantiating an Associate object and assigning properties to it from txtboxes inside of my main form. What is the best practice for null checking? Is it to check each and every property with an if statement before I assign it or is there something a bit better? Here is my code:
Associate updateAssociate = new Associate();
updateAssociate.AssocID = txtAssocId.Text;
updateAssociate.FirstName = txtFname.Text;
updateAssociate.LastName = txtLname.Text;
updateAssociate.HireDate = Convert.ToDateTime(txtHireDate.Text);
updateAssociate.ContractEndDate = Convert.ToDateTime(txtContractEnd.Text);
updateAssociate.TerminationDate = Convert.ToDateTime(txtTerminationDate.Text);
updateAssociate.FullPartTimeID = cboFullPart.SelectedText;
updateAssociate.PrimaryRole = cboPRole.SelectedText;
Based on your comment to the question:
If it is a text box then it would be the .Text property I would want to check for null or blank values before I assign them to the object
You can use the null coalescing operator to check for null values when assigning like that:
updateAssociate.AssocID = txtAssocId.Text ?? string.Empty;
or:
updateAssociate.AssocID = txtAssocId.Text ?? someDefaultValue;
That way if txtAssocId.Text is null then you would assign your defined default to the object property instead of null.
Though I'm not entirely sure a TextBox's .Text property would ever be null instead of an empty string. Maybe you want to check for both?:
updateAssociate.AssocID = string.IsNullOrEmpty(txtAssocId.Text) ? someDefaultValue : txtAssocId.Text;
In C# 6 it would be null-conditional operator.
updateAssociate.AssocID = txtAssocId?.Text;
In prior versions of c# you can write a method to eliminate code duplication. Something like this:
public static T CheckNull<T>(Func<T> canBeNull) where T : class
{
try
{
return canBeNull();
}
catch (NullReferenceException)
{
return default(T);
}
}
And use it like this
updateAssociate.AssocID = CheckNull(() => txtAssocId.Text);
Then you can wrap any code that can throw a null reference into lambda, pass it to this method and no longer bother with it.
I want to check that session is null or empty i.e. some thing like this:
if(Session["emp_num"] != null)
{
if (!string.IsNullOrEmpty(Session["emp_num"].ToString()))
{
//The code
}
}
Or just
if(Session["emp_num"] != null)
{
// The code
}
because sometimes when i check only with:
if (!string.IsNullOrEmpty(Session["emp_num"].ToString()))
{
//The code
}
I face the following exception:
Null Reference exception
Use this if the session variable emp_num will store a string:
if (!string.IsNullOrEmpty(Session["emp_num"] as string))
{
//The code
}
If it doesn't store a string, but some other type, you should just check for null before accessing the value, as in your second example.
if (HttpContext.Current.Session["emp_num"] != null)
{
// code if session is not null
}
if at all above fails.
You need to check that Session["emp_num"] is not null before trying to convert it to a string otherwise you will get a null reference exception.
I'd go with your first example - but you could make it slightly more "elegant".
There are a couple of ways, but the ones that springs to mind are:
if (Session["emp_num"] is string)
{
}
or
if (!string.IsNullOrEmpty(Session["emp_num"] as string))
{
}
This will return null if the variable doesn't exist or isn't a string.
You should first check if Session["emp_num"] exists in the session.
You can ask the session object if its indexer has the emp_num value or use string.IsNullOrEmpty(Session["emp_num"])
If It is simple Session you can apply NULL Check directly Session["emp_num"] != null
But if it's a session of a list Item then You need to apply any one of the following option
Option 1:
if (((List<int>)(Session["emp_num"])) != null && (List<int>)Session["emp_num"])).Count > 0)
{
//Your Logic here
}
Option 2:
List<int> val= Session["emp_num"] as List<int>; //Get the value from Session.
if (val.FirstOrDefault() != null)
{
//Your Logic here
}
Check if the session is empty or not in C# MVC Version Lower than 5.
if (!string.IsNullOrEmpty(Session["emp_num"] as string))
{
//cast it and use it
//business logic
}
Check if the session is empty or not in C# MVC Version Above 5.
if(Session["emp_num"] != null)
{
//cast it and use it
//business logic
}
I'm using C# to write a simple program to read Active Directory and display the value held in a AD field on a Windows form program.
If a property doesn't exist then the program crashes, below is my code, how can I catch this and move on to the next field without doing a try/catch for each and every attribute?
DirectoryEntry usr = new DirectoryEntry("LDAP://" + domain, username, password);
DirectorySearcher searcher = new DirectorySearcher(usr);
searcher.Filter = "(sAMAccountName=" + GlobalClass.strUserName + ")";
searcher.CacheResults = false;
searcher.SearchScope = SearchScope.Subtree;
searcher.PropertiesToLoad.Add("givenName");
searcher.PropertiesToLoad.Add("telephoneNumber");
//program crashes here if telephoneNumber attribute doesn't exist.
textBoxFirstName.Text = usr.Properties["telephoneNumber"].Value.ToString();
Just checking usr.Properties["telephoneNumber"] will not work. You must check the actual value. The reason the error is occuring is because you're calling ToString() on Value which is null.
user.Properties will always return a PropertyValueCollection, regardless of the property name entered into the collections indexer.
I.e.
var pony = usr.Properties["OMG_PONIES"]; // Will return a PropertyValueCollection
var value = pony.Value; // Will return null and not error
You need to check the value itself, the best way through the null coalescing operator:
textBoxFirstName.Text = (usr.Properties["telephoneNumber"].Value
?? "Not found").ToString();
Store the contents of usr.Properties["telephoneNumber"]; in a variable and check for null:
PropertyValueCollection tel = usr.Properties["telephoneNumber"];
textBoxFirstName.Text = (tel != null && tel.Value != null)
? tel.Value.ToString()
: "";
Use the null-coalescing operator (??) operator.
textBoxFirstName.Text = (usr.Properties["telephoneNumber"].Value
?? String.Empty).ToString();
This way the value is replaced with an empty string if null. You could also just return null instead of String.Empty, the reason your code is crashing is because you're trying to call ToString() on a null value.
Something like this should work. If telephoneNumber is not null, it will convert the value to a string, otherwise it will use an empty string.
textBoxFirstName.Text = usr.Properties["telephoneNumber"].Value != null
? usr.Properties["telephoneNumber"].Value.ToString()
: "";
A couple of things will help this be more graceful:
Test usr.Properties["telephoneNumber"] for null before calling child properties like Value. I haven't worked with AD myself, but most string-keyed indexers are designed to gracefully handle non-existent keys. the CLR, on the other hand, will happily throw a NullReferenceException any time you try to reference a member of anything that evaluates to null.
On the off chance that AD DOES blow up on a nonexistent column, enclose the assignment in a Try-Catch block that will show an error on the screen and gracefully continue processing (or not).
Use this code
SearchResult.Properties.Contains("property")
To check if the object actually has the prop loaded from the search result
if (usr.Properties["telephoneNumber"] != null)
textBoxFirstName.Text = usr.Properties["telephoneNumber"].Value.ToString();