Here's code I write to check if properties in my viewmodel are null or not before attempting to update the database
var channel = _context.Channels.FirstOrDefault(x => x.Id == viewModel.Id);
if (!string.IsNullOrEmpty(viewModel.Part))
{
channel.Part = viewModel.Part;
}
if (!string.IsNullOrEmpty(viewModel.IndexName))
{
channel.IndexName = viewModel.IndexName;
}
if (viewModel.MeasurementId != null)
{
channel.MeasurementId = viewModel.MeasurementId;
}
if (!string.IsNullOrEmpty(viewModel.Direction))
{
channel.Direction = viewModel.Direction;
}
The code is working fine but I use alot of if statements here which for me doesn't look really effective. Can you suggest me changes like using other syntax or structures rather than if statement to make my code more concise and abit more "pro"?
As long as your channel object's properties do not have any side-effects other than changing a value (ie, firing events), you could do this:
string PickNonEmptyOrDefault(string value, string deflt)
{
return String.IsNullOrEmpty(value) ? deflt : value;
}
...
channel.Part = PickNonEmptyOrDefault(viewModel.Part, channel.Part);
channel.IndexName = PickNonEmptyOrDefault(viewModel.IndexName, channel.IndexName);
etc.
By the way, I wanted to know if there was a way this could be done without accidentally side effecting your property. The trick is to use reflection and to use a PropertyInfo object to do your work:
class Foo
{
public string Bar { get; set; }
public string Baz { get; set; }
public override string ToString()
{
return (Bar ?? "") + " " + (Baz ?? "");
}
}
delegate void propsetter(string prop, string value);
private static void SetOnNonEmpty(PropertyInfo pi, Object o, string value)
{
if (pi.PropertyType != typeof(string))
throw new ArgumentException("type mismatch on property");
if (!String.IsNullOrEmpty(value))
pi.SetValue(o, value);
}
static void Main(string[] args)
{
var myObj = new Foo();
myObj.Baz = "nothing";
PropertyInfo piBar = myObj.GetType().GetProperty("Bar");
PropertyInfo piBaz = myObj.GetType().GetProperty("Baz");
SetOnNonEmpty(piBar, myObj, "something");
SetOnNonEmpty(piBaz, myObj, null);
Console.WriteLine(myObj);
}
output something nothing
I honestly don't recommend doing this as it doesn't really add to the readability and feels pretty gross.
I'd be more inclined to write a chunk of code that reflects across the properties of your view model and calls a Func<string, string> to get the corresponding property name in your data model and then if that returns non-null and the property types match, call the getter on the view object and pass it to the setter on the data object.
And I would only do this if I was doing this a significant number of times.
If it's just the if that bothers you you could use the conditional operator:
channel.Part = string.IsNullOrEmpty(viewModel.Part) ?
channel.Part : viewModel.Part;
etc.
of course that always calls the set accessor for Part, which is fine unless there's logic in it (change tracking, etc.) that would be bad if it were called when the value doesn't really change.
You could also refactor the conditional operator to a method, but there's no other way to conditionally set the value without using an if.
Your code is fine. Even Jon Skeet uses if statements.
If you want the best performing code, keep it like this. If you want to make your code look pro, use any suggestion done by others here. My opinion: keep it as is.
There is absolutely nothing wrong with the code you have written.
If your objective is less lines of code, you can do this, however I think it will just add unnecessary complexity.
channel.Part = string.IsNullOrWhiteSpace(viewModel.Part) ? channel.Part : viewModel.Part;
channel.IndexName = string.IsNullOrWhiteSpace(viewModel.IndexName) ? channel.IndexName: viewModel.IndexName;
channel.MeasurementId = viewModel.MeasurementId == null ? channel.MeasurementId : viewModel.MeasurementId;
channel.Direction = string.IsNullOrWhiteSpace(viewModel.Direction) ? channel.Direction : viewModel.Direction;
Note I have switched your call from IsNullOrEmpty to IsNullOrWhiteSpace
A string with the value of " " (one or more whitespace) will get through a IsNullOrEmpty check which you probably dont want.
You can also use the coalesce operator for your nullable types (but not empty strings) like this...
channel.MeasurementId = viewModel.MeasurementId ?? channel.MeasurementId;
If those are fields and not properties, you can use something like this:
void ReplaceIfNotEmpty(ref string destination, string source)
{
if (!string.IsNullOrEmpty(source))
{
destination = source;
}
}
and then just
ReplaceIfNotEmpty(ref channel.Part, viewModel.Part);
What is the fastest way (in terms of minimizing the amount of code statements) to get a property from an object after checking that the object isn't null?
string s = null;
if (null != myObject)
{
s = myObject.propertyName;
}
For reference: Wait for future C# 6.0 feature for null checking with possible ?. syntax:
string result = obj?.ToString();
For now: Use ternary operator:
string result = obj != null ? obj.ToString() : null;
C# does not have a null-propagating operator (although it has been discussed a few times). Frankly, "faster" is not likely to be a factor here, as it will typically end up in the same (or similar enough) IL, but I tend to use:
string s = myObject == null ? null : myObject.PropertyName;
the situation you describe is only one scenario where the operator is useful. It's also handy to replace constructs like this:
if (value != null)
{
return value;
}
else
{
return otherValue;
}
Or
return value != null ? value : otherValue;
with
return value ?? otherValue;
I am using gridview's default update method in which it allows me to update row in gridview itself by converting cells into textboxes.
I want to check validations that if a particular textbox (cell) remains empty or blank then it should not update its value.
For that i have written following code:
string.IsNullOrEmpty(e.NewValues[0].ToString())
But it gives an error like object reference not set to an instance of an object. May be it can not convert null value of e.Newvalues[0] to string.
All answers are appreciated in advance.
You could do this:
e.NewValues[0] == null || e.NewValues[0].ToString() == string.Empty
If e.NewValues[0] is already a string, you could just do this:
string.IsNullOrEmpty(e.NewValues[0])
Update as of C# 6, you could also use:
string.IsNullOrEmpty(e.NewValues[0]?.ToString())
Or even:
$"{e.NewValues[0]}" == string.Empty
Another way:
String.IsNullOrEmpty(Convert.ToString(e.NewValues[0]));
A bit of (probably unneeded) explanation:
Convert.ToString() will return null for a (string)null, and an empty string for an (object)null (or any other null).
Either case will give the expected result, because we're checking with String.IsNullOrEmpty().
In any case, its behaviour is the same as someValue.ToString() except it handles the cases where someValue is null.
Another (wasteful) way to do it is with a singleton with an overridden ToString and ?? (overkill but it lets me use ?? :P)
(e.NewValues[0] ?? Empty._).ToString();
The code for the singleton is here:
public sealed class Empty
{
private static readonly Lazy<Empty> lazy =
new Lazy<Empty>(() => new Empty());
public override string ToString()
{
return "";
}
public static object _ { get { return lazy.Value; } }
private Empty()
{
}
}
You can use this piece of code
(e.NewValues[0] == null) ? string.Empty : e.NewValues[0].ToString()
The above code will will return the string equivalent if not null, otherwise it will return empty string.
Otherwise you can use following code. This will handle the null case.
string.IsNullOrEmpty(Convert.ToString( e.NewValues[0] )
You'll need to check that e.NewValues[0] isn't null prior to doing a .ToString() on it.
protected void grd_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = grd.Rows[e.RowIndex];
for (int i = 0; i <= row.Cells.Count; i++)
{
String str = ((TextBox)(row.Cells[i].Controls[0])).Text;
if (!string.IsNullOrEmpty(str))
{
//Your Code goes here ::
}
}
}
Note: This question was asked before the introduction of the .? operator in C# 6 / Visual Studio 2015.
We've all been there, we have some deep property like cake.frosting.berries.loader that we need to check if it's null so there's no exception. The way to do is is to use a short-circuiting if statement
if (cake != null && cake.frosting != null && cake.frosting.berries != null) ...
This is not exactly elegant, and there should perhaps be an easier way to check the entire chain and see if it comes up against a null variable/property.
Is it possible using some extension method or would it be a language feature, or is it just a bad idea?
We have considered adding a new operation "?." to the language that has the semantics you want. (And it has been added now; see below.) That is, you'd say
cake?.frosting?.berries?.loader
and the compiler would generate all the short-circuiting checks for you.
It didn't make the bar for C# 4. Perhaps for a hypothetical future version of the language.
Update (2014):
The ?. operator is now planned for the next Roslyn compiler release. Note that there is still some debate over the exact syntactic and semantic analysis of the operator.
Update (July 2015): Visual Studio 2015 has been released and ships with a C# compiler that supports the null-conditional operators ?. and ?[].
I got inspired by this question to try and find out how this kind of deep null checking can be done with an easier / prettier syntax using expression trees. While I do agree with the answers stating that it might be a bad design if you often need to access instances deep in the hierarchy, I also do think that in some cases, such as data presentation, it can be very useful.
So I created an extension method, that will allow you to write:
var berries = cake.IfNotNull(c => c.Frosting.Berries);
This will return the Berries if no part of the expression is null. If null is encountered, null is returned. There are some caveats though, in the current version it will only work with simple member access, and it only works on .NET Framework 4, because it uses the MemberExpression.Update method, which is new in v4. This is the code for the IfNotNull extension method:
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace dr.IfNotNullOperator.PoC
{
public static class ObjectExtensions
{
public static TResult IfNotNull<TArg,TResult>(this TArg arg, Expression<Func<TArg,TResult>> expression)
{
if (expression == null)
throw new ArgumentNullException("expression");
if (ReferenceEquals(arg, null))
return default(TResult);
var stack = new Stack<MemberExpression>();
var expr = expression.Body as MemberExpression;
while(expr != null)
{
stack.Push(expr);
expr = expr.Expression as MemberExpression;
}
if (stack.Count == 0 || !(stack.Peek().Expression is ParameterExpression))
throw new ApplicationException(String.Format("The expression '{0}' contains unsupported constructs.",
expression));
object a = arg;
while(stack.Count > 0)
{
expr = stack.Pop();
var p = expr.Expression as ParameterExpression;
if (p == null)
{
p = Expression.Parameter(a.GetType(), "x");
expr = expr.Update(p);
}
var lambda = Expression.Lambda(expr, p);
Delegate t = lambda.Compile();
a = t.DynamicInvoke(a);
if (ReferenceEquals(a, null))
return default(TResult);
}
return (TResult)a;
}
}
}
It works by examining the expression tree representing your expression, and evaluating the parts one after the other; each time checking that the result is not null.
I am sure this could be extended so that other expressions than MemberExpression is supported. Consider this as proof-of-concept code, and please keep in mind that there will be a performance penalty by using it (which will probably not matter in many cases, but don't use it in a tight loop :-) )
I've found this extension to be quite useful for deep nesting scenarios.
public static R Coal<T, R>(this T obj, Func<T, R> f)
where T : class
{
return obj != null ? f(obj) : default(R);
}
It's an idea I derrived from the null coalescing operator in C# and T-SQL. The nice thing is that the return type is always the return type of the inner property.
That way you can do this:
var berries = cake.Coal(x => x.frosting).Coal(x => x.berries);
...or a slight variation of the above:
var berries = cake.Coal(x => x.frosting, x => x.berries);
It's not the best syntax I know, but it does work.
Besides violating the Law of Demeter, as Mehrdad Afshari has already pointed out, it seems to me you need "deep null checking" for decision logic.
This is most often the case when you want to replace empty objects with default values. In this case you should consider implementing the Null Object Pattern. It acts as a stand-in for a real object, providing default values and "non-action" methods.
Update: Starting with Visual Studio 2015, the C# compiler (language version 6) now recognizes the ?. operator, which makes "deep null checking" a breeze. See this answer for details.
Apart from re-designing your code, like
this deleted answer suggested,
another (albeit terrible) option would be to use a try…catch block to see if a NullReferenceException occurs sometime during that deep property lookup.
try
{
var x = cake.frosting.berries.loader;
...
}
catch (NullReferenceException ex)
{
// either one of cake, frosting, or berries was null
...
}
I personally wouldn't do this for the following reasons:
It doesn't look nice.
It uses exception handling, which should target exceptional situations and not something that you expect to happen often during the normal course of operation.
NullReferenceExceptions should probably never be caught explicitly. (See this question.)
So is it possible using some extension method or would it be a language feature, [...]
This would almost certainly have to be a language feature (which is available in C# 6 in the form of the .? and ?[] operators), unless C# already had more sophisticated lazy evaluation, or unless you want to use reflection (which probably also isn't a good idea for reasons of performance and type-safety).
Since there's no way to simply pass cake.frosting.berries.loader to a function (it would be evaluated and throw a null reference exception), you would have to implement a general look-up method in the following way: It takes in an objects and the names of properties to look up:
static object LookupProperty( object startingPoint, params string[] lookupChain )
{
// 1. if 'startingPoint' is null, return null, or throw an exception.
// 2. recursively look up one property/field after the other from 'lookupChain',
// using reflection.
// 3. if one lookup is not possible, return null, or throw an exception.
// 3. return the last property/field's value.
}
...
var x = LookupProperty( cake, "frosting", "berries", "loader" );
(Note: code edited.)
You quickly see several problems with such an approach. First, you don't get any type safety and possible boxing of property values of a simple type. Second, you can either return null if something goes wrong, and you will have to check for this in your calling function, or you throw an exception, and you're back to where you started. Third, it might be slow. Fourth, it looks uglier than what you started with.
[...], or is it just a bad idea?
I'd either stay with:
if (cake != null && cake.frosting != null && ...) ...
or go with the above answer by Mehrdad Afshari.
P.S.: Back when I wrote this answer, I obviously didn't consider expression trees for lambda functions; see e.g. #driis' answer for a solution in this direction. It's also based on a kind of reflection and thus might not perform quite as well as a simpler solution (if (… != null & … != null) …), but it may be judged nicer from a syntax point-of-view.
While driis' answer is interesting, I think it's a bit too expensive performance wise. Rather than compiling many delegates, I'd prefer to compile one lambda per property path, cache it and then reinvoke it many types.
NullCoalesce below does just that, it returns a new lambda expression with null checks and a return of default(TResult) in case any path is null.
Example:
NullCoalesce((Process p) => p.StartInfo.FileName)
Will return an expression
(Process p) => (p != null && p.StartInfo != null ? p.StartInfo.FileName : default(string));
Code:
static void Main(string[] args)
{
var converted = NullCoalesce((MethodInfo p) => p.DeclaringType.Assembly.Evidence.Locked);
var converted2 = NullCoalesce((string[] s) => s.Length);
}
private static Expression<Func<TSource, TResult>> NullCoalesce<TSource, TResult>(Expression<Func<TSource, TResult>> lambdaExpression)
{
var test = GetTest(lambdaExpression.Body);
if (test != null)
{
return Expression.Lambda<Func<TSource, TResult>>(
Expression.Condition(
test,
lambdaExpression.Body,
Expression.Default(
typeof(TResult)
)
),
lambdaExpression.Parameters
);
}
return lambdaExpression;
}
private static Expression GetTest(Expression expression)
{
Expression container;
switch (expression.NodeType)
{
case ExpressionType.ArrayLength:
container = ((UnaryExpression)expression).Operand;
break;
case ExpressionType.MemberAccess:
if ((container = ((MemberExpression)expression).Expression) == null)
{
return null;
}
break;
default:
return null;
}
var baseTest = GetTest(container);
if (!container.Type.IsValueType)
{
var containerNotNull = Expression.NotEqual(
container,
Expression.Default(
container.Type
)
);
return (baseTest == null ?
containerNotNull :
Expression.AndAlso(
baseTest,
containerNotNull
)
);
}
return baseTest;
}
One option is to use the Null Object Patten, so instead of having null when you don’t have a cake, you have a NullCake that returns a NullFosting etc. Sorry I am not very good at explaining this but other people are, see
An example of the Null Object Patten usage
The wikipedai write up on the Null Object Patten
I too have often wished for a simpler syntax! It gets especially ugly when you have method-return-values that might be null, because then you need extra variables (for example: cake.frosting.flavors.FirstOrDefault().loader)
However, here's a pretty decent alternative that I use: create an Null-Safe-Chain helper method. I realize that this is pretty similar to #John's answer above (with the Coal extension method) but I find it's more straightforward and less typing. Here's what it looks like:
var loader = NullSafe.Chain(cake, c=>c.frosting, f=>f.berries, b=>b.loader);
Here's the implementation:
public static TResult Chain<TA,TB,TC,TResult>(TA a, Func<TA,TB> b, Func<TB,TC> c, Func<TC,TResult> r)
where TA:class where TB:class where TC:class {
if (a == null) return default(TResult);
var B = b(a);
if (B == null) return default(TResult);
var C = c(B);
if (C == null) return default(TResult);
return r(C);
}
I also created several overloads (with 2 to 6 parameters), as well as overloads that allow the chain to end with a value-type or default. This works really well for me!
There is Maybe codeplex project that Implements
Maybe or IfNotNull using lambdas for deep expressions in C#
Example of use:
int? CityId= employee.Maybe(e=>e.Person.Address.City);
The link was suggested in a similar question How to check for nulls in a deep lambda expression?
As suggested in John Leidegren's answer, one approach to work-around this is to use extension methods and delegates. Using them could look something like this:
int? numberOfBerries = cake
.NullOr(c => c.Frosting)
.NullOr(f => f.Berries)
.NullOr(b => b.Count());
The implementation is messy because you need to get it to work for value types, reference types and nullable value types. You can find a complete implementation in Timwi's answer to What is the proper way to check for null values?.
Or you may use reflection :)
Reflection function:
public Object GetPropValue(String name, Object obj)
{
foreach (String part in name.Split('.'))
{
if (obj == null) { return null; }
Type type = obj.GetType();
PropertyInfo info = type.GetProperty(part);
if (info == null) { return null; }
obj = info.GetValue(obj, null);
}
return obj;
}
Usage:
object test1 = GetPropValue("PropertyA.PropertyB.PropertyC",obj);
My Case(return DBNull.Value instead of null in reflection function):
cmd.Parameters.AddWithValue("CustomerContactEmail", GetPropValue("AccountingCustomerParty.Party.Contact.ElectronicMail.Value", eInvoiceType));
Try this code:
/// <summary>
/// check deep property
/// </summary>
/// <param name="obj">instance</param>
/// <param name="property">deep property not include instance name example "A.B.C.D.E"</param>
/// <returns>if null return true else return false</returns>
public static bool IsNull(this object obj, string property)
{
if (string.IsNullOrEmpty(property) || string.IsNullOrEmpty(property.Trim())) throw new Exception("Parameter : property is empty");
if (obj != null)
{
string[] deep = property.Split('.');
object instance = obj;
Type objType = instance.GetType();
PropertyInfo propertyInfo;
foreach (string p in deep)
{
propertyInfo = objType.GetProperty(p);
if (propertyInfo == null) throw new Exception("No property : " + p);
instance = propertyInfo.GetValue(instance, null);
if (instance != null)
objType = instance.GetType();
else
return true;
}
return false;
}
else
return true;
}
I posted this last night and then a friend pointed me to this question. Hope it helps. You can then do something like this:
var color = Dis.OrDat<string>(() => cake.frosting.berries.color, "blue");
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
namespace DeepNullCoalescence
{
public static class Dis
{
public static T OrDat<T>(Expression<Func><T>> expr, T dat)
{
try
{
var func = expr.Compile();
var result = func.Invoke();
return result ?? dat; //now we can coalesce
}
catch (NullReferenceException)
{
return dat;
}
}
}
}
Read the full blog post here.
The same friend also suggested that you watch this.
I slightly modified the code from here to make it work for the question asked:
public static class GetValueOrDefaultExtension
{
public static TResult GetValueOrDefault<TSource, TResult>(this TSource source, Func<TSource, TResult> selector)
{
try { return selector(source); }
catch { return default(TResult); }
}
}
And yes, this is probably not the optimal solution due to try/catch performance implications but it works :>
Usage:
var val = cake.GetValueOrDefault(x => x.frosting.berries.loader);
Where you need to achieve this, do this:
Usage
Color color = someOrder.ComplexGet(x => x.Customer.LastOrder.Product.Color);
or
Color color = Complex.Get(() => someOrder.Customer.LastOrder.Product.Color);
Helper class implementation
public static class Complex
{
public static T1 ComplexGet<T1, T2>(this T2 root, Func<T2, T1> func)
{
return Get(() => func(root));
}
public static T Get<T>(Func<T> func)
{
try
{
return func();
}
catch (Exception)
{
return default(T);
}
}
}
I like approach taken by Objective-C:
"The Objective-C language takes another approach to this problem and does not invoke methods on nil but instead returns nil for all such invocations."
if (cake.frosting.berries != null)
{
var str = cake.frosting.berries...;
}
Is there a better way to write this code..
MyObject pymt = new MyObject();
pymt.xcol1id= Convert.IsDBNull(row["col1id"]) ? 0 : (int)row["col1id"];
pymt.xcold2id= Convert.IsDBNull(row["col2id"]) ? String.Empty : (string)row["col2id"];
pymt.xcold3id = Convert.IsDBNull(row["CustNum"]) ? 0 : (decimal)row["xcold3id"];
could this be done in a cleaner way .. like generic methods etc??
You could make generic extension methods like this:
public static class DataRowExtensions {
public static T GetValueOrDefault<T>(this DataRow row, string key) {
return row.GetValueOrDefault(key, default(T));
}
public static T GetValueOrDefault<T>(this DataRow row, string key, T defaultValue) {
if (row.IsNull(key)) {
return defaultValue;
} else {
return (T)row[key];
}
}
}
Usage:
MyObject pymt = new MyObject();
pymt.xcol1id = row.GetValueOrDefault<int>("col1id");
pymt.xcold2id = row.GetValueOrDefault<string>("col2id", String.Empty);
pymt.xcold3id = row.GetValueOrDefault<int>("CustNum"]);
Absolutely there's a cleaner way to write that code if you're using .NET 3.5, and without re-inventing extension methods that Microsoft already wrote for you. Just add a reference to System.Data.DataSetExtensions.dll, and you'll be able to do this:
MyObject pymt = new MyObject
{
xcol1id = row.Field<int?>("col1id") ?? 0,
xcol2id = row.Field<string>("col2id") ?? String.Empty,
xcol3id = row.Field<decimal?>("col3id") ?? 0M
};
I tend to use the null coalescing operator in situations like those. Also, DBNull.ToString returns string.Empty, so you don't have to do anything fancy there.
MyObject pymt = new MyObject();
pymt.xcol1id= row["col1id"] as int? ?? 0;
pymt.xcold2id= row["col2id"].ToString();
pymt.xcold3id = row["CustNum"] as decimal? ?? 0;
Better yet, add it as an extension method to the DataRow:
static T GetValueOrDefault<T>(this DataRow row, string columnName)
{
if (!row.IsNull(columnName))
{
// Might want to support type conversion using Convert.ChangeType().
return (T)row[columnName]
}
return default(T);
}
You can use it like:
pymt.xcol1id = row.GetValueOrDefault<int>("col1id");
pymt.xcol2id = row.GetValueOrDefault<string>("col2id");
pymt.xcol3id = row.GetValueOrDefault<decimal>("col3id");
static ToType GenericConvert<ToType>(object value)
{
ToType convValue = default(ToType);
if (!Convert.IsDBNull(value))
convValue = (ToType)value;
return convValue;
}
MyObject pymt = new MyObject();
pymt.xcol1id= GenericConvert<int>(row["col1id"]);
pymt.xcold2id= GenericConvert<string>(row["col2id"]) ?? String.Empty;
pymt.xcold3id = GenericConvert<decimal>(row["CustNum"]);
I actually like that. Our team had been using if/else statements which are more difficult to read in my opinion.
if (row["col1id"] == dbnull.value)
pymt.xcol1id = 0;
else
pymt.xcol1id = (int)row["col1id"];
Your code is easier to read because it places each assignment on individual lines.
A function as suggested by Stan might make the lines shorter but it hides the fact that nulls are being replaced unless you give it a very verbose name.
Some alternatives I can quickly think of:
Strongly typed datasets
Use the SqlTypes readers like ReadSqlInt32 since they all implement INullable.
Generate the code with XSLT transformation from XML, so the checking code is easy to change and maintain.