How to check for null in nested references - c#

Looking for some best-practice guidance. Let's say I have a line of code like this:
Color color = someOrder.Customer.LastOrder.Product.Color;
where Customer, LastOrder, Product, and Color could be null under normal conditions. I'd like color to be null if any one of the objects in the path is null, however; in order to avoid null reference exceptions, I'd need to check for the null condition for each one of the objects, e.g.
Color color = someOrder == null ||
someOrder.Customer == null ||
someOrder.Customer.LastOrder == null ||
someOrder.Customer.Product == null ?
null : someOrder.Customer.LastOrder.Product.Color;
or I could do this
Color color = null;
try {color = someOrder.Customer.LastOrder.Product.Color}
catch (NullReferenceException) {}
The first method clearly works, but it seems a bit more tedious to code and harder to read. The second way is a bit easier but probably not a good idea to use exception handling for this.
Is there another shortcut way of checking for nulls and assigning null to color if necessary? Or any thoughts on how to avoid NullReferenceExceptions when using such nested references?

You are looking for the null-safe dereferencing operator.
Color color = someOrder?.Customer?.LastOrder?.Product?.Color;
Unfortunately C# doesn't support it. Maybe it will be added later, but there are no plans to do that at the moment.
Related
Deep null checking, is there a better way?

Best practice is to follow Law of Demeter which sounds as: don't talk to strangers. I.e. object should avoid invoking methods of a member object returned by another method. This allows to write less coupled, more maintainable and readable code.
So, avoid using 'train wrecks' like someOrder.Customer.LastOrder.Product.Color, because they completely violate Law of Demeter. It's even hard to understand what business meaning this code has. Why are you getting color of product of some other order, which is not the current one?
Possible way to remove train wreck - push functionality closer to interesting end of wreck. In your case, also consider passing last product to your method, instead of using some order.

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 would definitely prefer the first method... the second one exploits the exception mechanism for program flow which is bad practice IMHO...
AFAIK there is no shortcut or "null-safe dereferencing operator" in C# .

Define unique method for accessing nested properties.
For example like this
private Customoer GetCustomer(Order order)
{
return order != null ? order.Customer : null;
}
private Order GetLastOrder(Customer customer)
{
return customer != null ? customer.LastOrder : null;
}
Using the defined method access your properties across the application

You can also use the Null-conditional operator in an if statement. Really useful if there is a lot of nested values.
Example:
public class DummyDto
{
public string Name { get; set; }
public DummyDto Parent { get; set; }
}
class Program
{
static void Main(string[] args)
{
var dummyDto = new DummyDto();
//Both if statements will be true below
if(dummyDto.Parent?.Name == null)
{
Console.WriteLine("DummyDto is null");
}
if (dummyDto.Parent == null || dummyDto.Parent.Name == null)
{
Console.WriteLine("DummyDto is null");
}
}
}

Related

Determine if an object has a property (set to null or anything else) [duplicate]

Using dynamic pattern perhaps? You can call any method/property using the dynamic keyword, right? How to check whether the method exist before calling myDynamicObject.DoStuff(), for example?
You could write something like that :
public static bool HasMethod(this object objectToCheck, string methodName)
{
var type = objectToCheck.GetType();
return type.GetMethod(methodName) != null;
}
Edit : you can even do an extension method and use it like this
myObject.HasMethod("SomeMethod");
via Reflection
var property = object.GetType().GetProperty("YourProperty")
property.SetValue(object,some_value,null);
Similar is for methods
It is an old question, but I just ran into it.
Type.GetMethod(string name) will throw an AmbiguousMatchException if there is more than one method with that name, so we better handle that case
public static bool HasMethod(this object objectToCheck, string methodName)
{
try
{
var type = objectToCheck.GetType();
return type.GetMethod(methodName) != null;
}
catch(AmbiguousMatchException)
{
// ambiguous means there is more than one result,
// which means: a method with that name does exist
return true;
}
}
Wouldn't it be better to not use any dynamic types for this, and let your class implement an interface.
Then, you can check at runtime wether an object implements that interface, and thus, has the expected method (or property).
public interface IMyInterface
{
void Somemethod();
}
IMyInterface x = anyObject as IMyInterface;
if( x != null )
{
x.Somemethod();
}
I think this is the only correct way.
The thing you're referring to is duck-typing, which is useful in scenarios where you already know that the object has the method, but the compiler cannot check for that.
This is useful in COM interop scenarios for instance. (check this article)
If you want to combine duck-typing with reflection for instance, then I think you're missing the goal of duck-typing.
To avoid AmbiguousMatchException, I would rather say
objectToCheck.GetType().GetMethods().Count(m => m.Name == method) > 0

C# HasValue in reference types

Is it somehow possible to use Nullable<>.HasValue on reference types?
Assume we have this example from value types:
int? a = GetNullOrValue(); // completely randomly gets random number or null
if (a.HasValue) return 0;
What I want to accomplish is this:
class Foo
{
public string Bar { get; set; }
}
Foo foo = GetNullOrFoo(); // completely randomly gets Foo ref. or null
if (foo.HasValue) return foo.Bar; // of course this will throw NullReferenceException if foo is null
I want to achieve this for better readability as I prefer "word stuff", not "symbol stuff" (x.HasValue instead of x != null).
You can write an extension method.
public static class Extension
{
public static bool HasValue<T>(this T self) where T : class
{
return self != null;
}
}
Then you can use
if (foo.HasValue()) return foo.Bar;
but, honestly x != null is simple, these kind of extension methods will be confusing for maintainers, I won't recommend it.
Also read further if you're going to use this approach. This will work only when there is no instance method named HasValue, if there is any instance method will be called, not the extension method. Hence it will result in NullReferenceException. Not to be surprised with the results. So think twice before you do this.
Always code as if the person who ends up maintaining your code is a
violent psychopath who knows where you live.
Quote from Code For The Maintainer

Syntactic sugar for throwing with null coalesce operator

Let's suppose we want to throw if we try to assign null to something, what about this trick:
public static class ExceptionExtension
{
public static T Throw<T>(this Exception exc)
{
throw exc;
}
}
that we can use for example like this:
return possibleNull ?? new Exception("Unspecified something....").Throw<string>();
do you think it is a good/worst/useless practice ?
It makes no sense to me - not very readable. I would expect the second argument of the ?? operator to be of the same type of possibleNull, not to throw an excpetion.
I would much rather see:
if(possibleNull == null)
{
throw new Exception("Unspecified something....");
}
return possibleNull;
It could be better and more readable to create some kind of static helper class that throws
Like this
public static class ThrowHelper
{
public static TException ThrowIfNull<TException>(object value)
where TException : Exception, new()
{
if (value == null) //or other checks
{
throw new TException();
}
}
}
You could always stick it in some sort of short-named static helper class:
public static class Never
{
public static T Null<T>(T value)
where T : class
{
if (value == null) throw new ArgumentNullException();
return value;
}
}
myClass.AProperty = Never.Null(somePotentiallyNullValue);
Your other example wouldn't make much sense, I'd opt for calling it "useless" practice.
Adding a bit of "fluency" to helper classes tends to focus on making things more readable.
http://en.wikipedia.org/wiki/Fluent_interface
I wouldn't consider it a good practice.
First, the extension method itself just introduces a method for something we already have a keyword for: throw. This might be confusing. It declares a return type though it will never return a value, just to please the compiler in the context where you want to use it. Referring to what others already pointed out, that's rather a "principle of most astonishment".
Then, looking on how you would employ this method, the resulting code seems not very clear to read. Even worse: you can only use this approach in an expression, so you would always end up with code that uses an object in some way (in your example: just return it) and checks it for null as a side effect in the same line. I'd prefer doing null checks explicitly and not mixed with something else. A library like CuttingEdge.Conditions can help to reduce the amount of code you have to type for this. You would use it in your example this way
Condition.Requires(possibleNull , "possibleNull ").IsNotNull();
return possibleNull;

Is it a bad thing to override == and have an instance compare equal to null?

Background
Let's say I have the following class:
public class MyValue<T>
{
public T Value { get; set; }
public static bool operator ==(MyValue<T> first, MyValue<T> second)
{
// if first and second are the same instance, they are equal
if (object.Equals(first, second))
{
return true;
}
// for each of the objects, get a value indicating whether either
// the object or its Value property is null
bool firstIsNull = object.Equals(first, null) ? true : first.Value == null;
bool secondIsNull = object.Equals(second, null) ? true : second.Value == null;
// if both are null, they are equal
if (firstIsNull && secondIsNull)
{
return true;
}
// Not both are null. If one is, they are not equal
if (firstIsNull || secondIsNull)
{
return false;
}
// Neither first nor second is null; compare their values
return first.Value.Equals(second.Value);
}
// more code implementing !=, Equals, GetHashCode, implicit conversions and so on
}
This class will be used as the type on properties in an object model. An object could look like so:
public class SomeClass
{
public SomeClass()
{
SomeValue = new MyValue<string>();
}
public MyValue<string> SomeValue { get; set; }
}
The idea with this is that the class simply represents the value of its Value property. It has some more functionality that is stripped away since it's not relevant for the question (some validation and stuff). Since the class has no value in itself, we want it to be as little intrusive as possible when used. Implicit conversions allows for code like this:
SomeClass instance = new SomeClass();
instance.SomeValue = "my string";
...and the question:
The idea with overloading the == (and !=) operator is to have an instance of the object where Value is null to compare equal to null (partly because we feel it makes sense, partly because of backwards compatibility issues in the object model):
MyValue<string> a = new MyValue<string>();
MyValue<string> b = null;
bool areTheyEqual = (a == b); // this will be true
This may of course seem a bit confusing, but given that MyClass is simply a wrapper, that in most of the code will be rather invisible, does it make sense to you too, or is it something really bad that we will regret for reasons that we overlooked?
In my opinion, == operator in C# is already confusing enough. If you overload it like that, you'll be increasing the possibility of confusion.
Class c = somethingEqualsToNullButNotNull;
if (c == null) { // true
}
object co = c;
if (co == null) { // false. WTF!?
}
You say you've already overridden Equals to provide the same behaviour. That means you've already broken the contract for Equals, which explicitly states:
- x.Equals(a null reference (Nothing in Visual Basic)) returns false.
Basically: no, don't do this. It will be confusing to users of the class.
Now Nullable<T> appears to break this rule:
int? x = new int?(); // Or int? x = null;
object o = null;
Console.WriteLine(x.Equals(o)); // True
... but in this case x isn't a reference, which is part of the contract description. The only way of making x a reference is to box the value, at which point x is null anyway. In your case, MyValue is a class so you can have a non-null reference which violates the contract.
If you override ==, then normally it is best to override .Equals to use the same logic.

Resolving a parameter name at runtime [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Finding the Variable Name passed to a Function in C#
In C#, is there a way (terser the better) to resolve the name of a parameter at runtime?
For example, in the following method, if you renamed the method parameter, you'd also have to remember to update the string literal passed to ArgumentNullException.
public void Woof(object resource)
{
if (resource == null)
{
throw new ArgumentNullException("resource");
}
// ..
}
One way:
static void Main(string[] args)
{
Console.WriteLine("Name is '{0}'", GetName(new {args}));
Console.ReadLine();
}
This code also requires a supporting function:
static string GetName<T>(T item) where T : class
{
var properties = typeof(T).GetProperties();
Enforce.That(properties.Length == 1);
return properties[0].Name;
}
Basically the code works by defining a new Anonymous Type with a single Property consisting of the parameter who's name you want. GetName() then uses reflection to extract the name of that Property.
There are more details here: http://abdullin.com/journal/2008/12/13/how-to-find-out-variable-or-parameter-name-in-c.html
Short answer: No, there isn't. (Is that terse enough? ;)
(EDIT: Justin's answer probably counts. It leaves a bad taste in my mouth, but it accomplishes the goal of "no need to put the parameter name into a string". I don't think I'd really count AOP though, as that's really changing to a completely different approach rather than answering the original question of getting a parameter name from within a method.)
Longer answer: There's a way to find out all the parameters of a method, but I don't think it's useful in this case.
Here's an example which displays the parameter names from a couple of methods:
using System;
using System.Reflection;
class Test
{
static void Main()
{
Foo(null);
Bar(null);
}
static void Foo(object resource)
{
PrintParameters(MethodBase.GetCurrentMethod());
}
static void Bar(object other)
{
PrintParameters(MethodBase.GetCurrentMethod());
}
static void PrintParameters(MethodBase method)
{
Console.WriteLine("{0}:", method.Name);
foreach (ParameterInfo parameter in method.GetParameters())
{
Console.WriteLine(" {0} {1}",
parameter.ParameterType,
parameter.Name);
}
}
}
So that does that, but if you have multiple parameters and you wanted to throw an appropriate exception, how would you know (in a safe way) which to use? Ideally you want something like:
public void Woof(object resource)
{
if (resource == null)
{
throw new ArgumentNullException(infoof(resource));
}
// ..
}
where the mythical infoof operator would return a ParameterInfo. Unfortunately this doesn't exist.
I dealt with this very same issue. There are a couple of ways of getting the parameter name but the most performant is to dip down into the IL. You can see an example of my implementation on my blog post on this very issue Taking the pain out of parameter validation.
The one caveat to this approach is you need to pass the parameter name in as a delegate but it is small price to pay for cleaner code:
public void SomeMethod(string value)
{
Validate.Argument(() => value).IsNotNull().IsNotEmpty();
}
Which is somewhat cleaner and clearer than:
public void SomeMethod(string value)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
if (value == string.Empty)
{
throw new ArgumentException("Value cannot be an empty string.", "value");
}
}
The static method approach has allowed me to chain a number of methods together in a fluent interface. Initially an Argument object is returned which only allows a basic null test which returns a ReferenceArgument object which can then have additional validation. If the object under test is a value type then different tests are available.
The API allows for a number of common tests but it would be hard to capture all the possible tests so to provide flexibility a generic test method allows an expression or function to be provided and in the case of the former the expression can actually be used as the error message.
My example only covers a few of the basics but you can easily expand the interface to check for ranges and throw ArgumentOutOfRangeExceptions or test objects inherit from a specific base class or implement an interface. There are some similar implementations but I have not as yet seen any that get the parameter name.
You can get this information using AOP. You can define an intercept that is invoked before method execution and throw the exception there. This also takes care of the problem that null checking is a cross-cutting concern.
PostSharp is a good simple implementation of AOP.
Here's what your code would look like (haven't tested, but it should get you very close)
[AttributeUsage(AttributeTargets.Parameter)]
public class CanBeNullAttribute : Attribute
{
private readonly bool canBeNull;
public CanBeNullAttribute()
: this(true)
{
}
public CanBeNullAttribute(bool canBeNull)
{
this.canBeNull = canBeNull;
}
public bool AllowNull
{
get { return canBeNull; }
}
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class EnforceNullConstraintAttribute : OnMethodInvocationAspect
{
public override void OnInvocation(MethodInvocationEventArgs eventArgs)
{
object[] arguments = eventArgs.GetArgumentArray();
ParameterInfo[] parameters = eventArgs.Delegate.Method.GetParameters();
for (int i = 0; i < arguments.Length; i++)
{
if (arguments[i] != null) continue;
foreach (CanBeNullAttribute attribute in parameters[i].GetCustomAttributes(typeof(CanBeNullAttribute), true))
{
if (!attribute.AllowNull) throw new ArgumentNullException(parameters[i].Name);
}
}
base.OnInvocation(eventArgs);
}
}
Now, you can modify your method:
[EnforceNullConstraint]
public void Woof([CanBeNull(false)] object resource)
{
// no need to check for null, PostSharp will weave it at compile time
// execute logic assured that "resource" is not null
}
You might want:
1)
public static void ThrowIfNull<T>(Expression<Func<T>> expr)
{
if (expr == null || expr.Compile()() != null) //the compile part is slow
return;
throw new ArgumentNullException(((MemberExpression)expr.Body).Member.Name);
}
or
2)
public static void ThrowIfNull<T>(Expression<Func<T>> expr)
{
if (expr == null)
return;
var param = (MemberExpression)expr.Body;
if (((FieldInfo)param.Member).GetValue(((ConstantExpression)param.Expression).Value) == null)
throw new ArgumentNullException(param.Member.Name);
}
And call it:
Class.ThrowIfNull(() => resource);
But that's not what you would want probably. Its also a lot slower 1) is abt 1000 times slower than 2). May be:
3)
public static void ThrowIfNull<T>(this T item) where T : class
{
if (item == null)
return;
var param = typeof(T).GetProperties()[0];
if (param.GetValue(item, null) == null)
throw new ArgumentNullException(param.Name);
}
And call it:
new { resource }.ThrowIfNull();
Cleaner, much faster than above 2! :)
You can also extend these methods for properties of objects. For eg.,
new { myClass.MyProperty1 }.ThrowIfNull();
You can cache property values to improve performance further as property names don't change during runtime. See related question Finding the variable name passed to a function

Categories