public
Created

Handling "null" values in a more dynamic fashion in C#

  • Download Gist
DynamicNull.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
 
namespace Einstein.Dynamic
{
 
/// <summary>
/// A special null indicator that can be used in place of null values in a dynamic context
/// which enhances the way nulls normally behave. For example, null reference exceptions
/// are not thrown when attempting to access properties of the null value. Any attempts to
/// set members of the null value or invoke methods on the null value will throw a
/// NullReferenceException.
/// See the example code for more information.
/// </summary>
/// <example>
/// // start with a value of type DynamicNull
/// // it must use the dynamic keyword.
/// // this value can be returned by other dynamic types in place of nulls
/// // see DynamicDictionaryAdapter for an example in action
/// dynamic x = DynamicNull.Value;
///
/// if ( x == null ) { Console.WriteLine("x is null!"); }
/// if ( x == DBNull.Value ) { Console.WriteLine("Also considered equal to DBNull!"); }
/// if ( !x ) { Console.WriteLine("x is false!"); }
/// if ( x ) { Console.WriteLine("x is not true so you won't see this."); }
///
/// int? y = x; // y is now null
/// int z = x; // z is now zero
/// </example>
public sealed class DynamicNull : DynamicObject
{
 
#region Fields
 
/// <summary>
/// A singleton instance of a null object that does not throw exceptions upon accessing
/// its non-existing members.
/// </summary>
public static readonly dynamic Value = new DynamicNull( );
 
#endregion
 
#region Constructors
 
private DynamicNull( )
{
}
 
#endregion
 
#region Methods
 
public static bool IsNull( dynamic obj )
{
 
if ( ReferenceEquals( obj, null ) ) {
return true;
}
 
if ( ReferenceEquals( obj, Type.Missing ) ) {
return true;
}
 
Type objType = obj.GetType( );
 
if ( objType == typeof( DynamicNull ) ) {
return true;
}
 
if ( objType == typeof( DBNull ) ) {
return true;
}
 
if ( objType == typeof( Missing ) ) {
return true;
}
 
return false;
 
}
 
public override bool Equals( object obj )
{
return IsNull( obj );
}
 
public override int GetHashCode( )
{
return 0;
}
 
public override IEnumerable<string> GetDynamicMemberNames( )
{
yield break;
}
 
public override bool TryBinaryOperation( BinaryOperationBinder binder, object arg, out object result )
{
 
WriteDebug( "[{0}] TryBinaryOperation(Operation={1})", binder.ReturnType, binder.Operation );
 
switch ( binder.Operation ) {
case ExpressionType.Equal: {
result = Equals( arg );
return true;
}
case ExpressionType.NotEqual: {
result = !Equals( arg );
return true;
}
case ExpressionType.GreaterThan:
case ExpressionType.GreaterThanOrEqual:
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual: {
result = false;
return true;
}
}
 
result = this;
return true;
 
}
 
public override bool TryConvert( ConvertBinder binder, out object result )
{
 
WriteDebug( "[{0}] TryConvert(Type={1}, Explicit={2})", binder.ReturnType, binder.Type, binder.Explicit );
 
if ( binder.Type == typeof( System.Collections.IEnumerable ) ) {
result = Enumerable.Empty<object>( );
return true;
}
 
if ( binder.Type == typeof( System.Collections.IEnumerator ) ) {
result = Enumerable.Empty<object>( ).GetEnumerator( );
return true;
}
 
if ( binder.Type.IsGenericType && binder.Type.GetGenericTypeDefinition( ) == typeof( Nullable<> ) ) {
result = null;
return true;
}
 
if ( binder.Type.IsValueType ) {
result = Activator.CreateInstance( binder.Type );
return true;
}
 
result = null;
return true;
 
}
 
public override bool TryGetIndex( GetIndexBinder binder, object[] indexes, out object result )
{
 
WriteDebug( "[{0}] TryGetIndex(Index={1})", binder.ReturnType, indexes[0] );
 
result = this;
return true;
 
}
 
public override bool TryGetMember( GetMemberBinder binder, out object result )
{
 
WriteDebug( "[{0}] TryGetMember(Name={1})", binder.ReturnType, binder.Name );
 
result = this;
return true;
 
}
 
public override bool TryInvoke( InvokeBinder binder, object[] args, out object result )
{
 
WriteDebug( "[{0}] TryInvoke()", binder.ReturnType );
 
throw new NullReferenceException( );
 
}
 
public override bool TryInvokeMember( InvokeMemberBinder binder, object[] args, out object result )
{
 
WriteDebug( "[{0}] TryInvokeMember(Name={1})", binder.ReturnType, binder.Name );
 
throw new NullReferenceException( );
 
}
 
public override bool TrySetIndex( SetIndexBinder binder, object[] indexes, object value )
{
 
WriteDebug( "[{0}] TrySetIndex(Index={1})", binder.ReturnType, indexes[0] );
 
throw new NullReferenceException( );
 
}
 
public override bool TrySetMember( SetMemberBinder binder, object value )
{
 
WriteDebug( "[{0}] TrySetMember(Name={1})", binder.ReturnType, binder.Name );
 
throw new NullReferenceException( );
 
}
 
public override bool TryUnaryOperation( UnaryOperationBinder binder, out object result )
{
 
WriteDebug( "[{0}] TryUnaryOperation(Operation={1})", binder.ReturnType, binder.Operation );
 
switch ( binder.Operation ) {
case ExpressionType.IsTrue: {
result = false;
return true;
}
case ExpressionType.IsFalse: {
result = true;
return true;
}
case ExpressionType.Not: {
result = true;
return true;
}
}
 
result = this;
return true;
 
}
 
private static void WriteDebug( string message, params object[] args )
{
 
Debugger.Log( 0, "DynamicNullObject", String.Format( message, args ) + Environment.NewLine );
 
}
 
#endregion
 
#region Operators
 
public static bool operator ==( DynamicNull obj, object other )
{
 
WriteDebug( "Operator ==" );
 
return IsNull( other );
 
}
 
public static bool operator !=( DynamicNull obj, object other )
{
 
WriteDebug( "Operator !=" );
 
return !IsNull( other );
 
}
 
#endregion
 
}
 
}
DynamicNullTests.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.CSharp.RuntimeBinder;
using Microsoft.VisualStudio.TestTools.UnitTesting;
 
namespace Einstein.Dynamic
{
 
[TestClass]
public class DynamicNullTests
{
 
[TestMethod]
public void DynamicNull_EqualsNull( )
{
 
dynamic x = DynamicNull.Value;
dynamic y = null;
 
Assert.IsTrue( x == y );
 
}
 
[TestMethod]
public void DynamicNull_IsNotTrue( )
{
 
dynamic x = DynamicNull.Value;
 
if ( x ) {
// this should not happen
Assert.Fail( "Derp!" );
}
 
}
 
[TestMethod]
public void DynamicNull_IsFalse( )
{
 
dynamic x = DynamicNull.Value;
 
if ( !x ) {
Assert.IsTrue( true, "this is ok!" );
}
else {
// this should not happen
Assert.Fail( "It was supposed to be false. :(" );
}
 
}
 
[TestMethod]
public void DynamicNull_CastsToNullableValueType( )
{
 
dynamic x = DynamicNull.Value;
int? y = x;
 
Assert.AreEqual( null, y );
 
}
 
[TestMethod]
public void DynamicNull_CastsToDefaultValueType( )
{
 
dynamic x = DynamicNull.Value;
int y = x;
 
Assert.AreEqual( 0, y );
 
}
 
[TestMethod]
public void DynamicNull_NotGreaterOrLessThanAnything( )
{
 
dynamic x = DynamicNull.Value;
 
Assert.IsFalse( x > Int32.MinValue );
Assert.IsFalse( x > Int32.MaxValue );
Assert.IsFalse( x > default( Int32 ) );
 
Assert.IsFalse( x >= Int32.MinValue );
Assert.IsFalse( x >= Int32.MaxValue );
Assert.IsFalse( x >= default( Int32 ) );
 
Assert.IsFalse( x < Int32.MinValue );
Assert.IsFalse( x < Int32.MaxValue );
Assert.IsFalse( x < default( Int32 ) );
 
Assert.IsFalse( x <= Int32.MinValue );
Assert.IsFalse( x <= Int32.MaxValue );
Assert.IsFalse( x <= default( Int32 ) );
 
}
 
[TestMethod]
public void DynamicNull_CoalescesPropertyAccess( )
{
 
dynamic x = DynamicNull.Value;
 
dynamic y = x.i.donot.exist;
 
Assert.IsTrue( y == null );
 
}
 
[TestMethod]
[ExpectedException( typeof( NullReferenceException ) )]
public void DynamicNull_ThrowsOnSetMember( )
{
 
dynamic x = DynamicNull.Value;
 
x.derp = "derp";
 
}
 
[TestMethod]
[ExpectedException( typeof( NullReferenceException ) )]
public void DynamicNull_ThrowsOnSetIndex( )
{
 
dynamic x = DynamicNull.Value;
 
x["derp"] = "derp";
 
}
 
[TestMethod]
[ExpectedException( typeof( NullReferenceException ) )]
public void DynamicNull_ThrowsOnInvokeMember( )
{
 
dynamic x = DynamicNull.Value;
 
x.derp( );
 
}
 
}
 
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.