The dreaded Possible 'InvalidOperationException'

 I don't know why I keep having a problem with this!  It works fine in the test solution I whipped up.

I have the following class in a common project:

public static class ObjectExtensions
{
[ContractAnnotation("obj: null => halt")]
public static void ThrowIfNull<T>(this T obj, string message = "") where T : class
{
if (string.IsNullOrWhiteSpace(message))
message = typeof(T).FullName + " cannot be null.";

if (obj == null)
throw new NullReferenceException(message);
}

[ContractAnnotation("obj: null => halt")]
public static void ThrowIfNull<T>(this T? obj, string message = "") where T : struct
{
if (string.IsNullOrWhiteSpace(message))
message = typeof(T).FullName + " cannot be null.";

if (obj == null)
throw new NullReferenceException(message);
}

[ContractAnnotation("null => true")]
public static bool IsNull(this object obj)
{
return obj == null;
}

[ContractAnnotation("null => false")]
public static bool IsNotNull(this object obj)
{
return obj != null;
}
}

But when I use it in another project that references this shared project, I get a possible Possible 'InvalidOperationException'

int? testInt1 = null;

if (DateTime.Now.Minute == 5)
testInt1 = 1;

testInt1.ThrowIfNull();

int testInt2 = testInt1.Value;

I'm using ReSharper 2017.3

Cheers

0
3 comments

Are you using a "release" build of the shared project? IIRC, the annotations from the NuGet package only apply to debug builds.

0
Avatar
Permanently deleted user

Ah, yes.  Of course.  Okay, I've resolved the immediate problem.  I had the project added to my solution, but I was still referencing a release build of my dll.  Switching this to a project reference (debug build) sorted it out.

In the long term though, I need to have the annotations built into the assembly, which I understand can be done by adding JETBRAINS_ANNOTATIONS to the Conditional compilation symbols of the project containing ObjectExtensions.

I'm trying to test both of these theories in my sample solution, but I can't seem to replicate the problem.  I have the ObjectExtensions project set to release and without the compilation symbol, but it won't complain about Possible 'InvalidOperationException's.

0
Avatar
Permanently deleted user

"it" being the project referencing the ObjectExtensions project.

0

Please sign in to leave a comment.