My class requires additional information to properly output its status, so I've added a custom PrintSelf method taking the appropriate parameters.
However, I'm afraid there are still calls to ToString in my large project, which were not replaced by the new method. How can I find those improper calls to ToString?
I'm using VS 2015, but it does not seem to have this ability.
Throwing an exception in ToString would be an obvious way, but I don't want to do that for two reasons:
ToString can still perform a different job and output something not depending on the added parameter.
There is no way to get full code coverage, meaning it would only find a few instances of implicit calls, but not (reliably) all of them.
To override ToString and log the caller you can do like this
public override string ToString()
{
StackTrace stackTrace = new StackTrace();
StackFrame[] stackFrames = stackTrace.GetFrames();
StackFrame callingFrame = stackFrames[1];
MethodInfo method = callingFrame.GetMethod();
YourLogingMethod(method.DeclaringType.Name + "." + method.Name);
return base.ToString();
}
You can make usage of the Obsolete Attribute :
public class MyFirstClass
{
//true or false parameters indicates whether to throw
// a compile error (true) or warning (false)
[Obsolete("Please use the method PrintSelf() instead of ToString()", false)]
public overrides string ToString()
{
//Whatever code you want here
return "";
}
}
public class MySecondClass
{
public void Test()
{
mfc = new MyFirstClass();
mfc.ToString(); //Here you will get a compiler warning
}
}
So this will let you know inside Visual Studio of all the calls made to this function. Since it is only a warning, it is still possible to use it.
(note : Sorry if the syntax is not correct, I'm normally a VB .Net developper, feel free to correct it if needed.)
I do not want to disable the warnings completely, just when it's in an Assert statement.
So for example if I have the following two lines
var someObject = GetObject();
Assert.IsNotNull(someObject, "someObject should not be null");
Assert.AreEqual(expectedValue, someObject.SomeProperty);
I'll get the possible null reference warning on the second line on someObject.SomeProperty. Is it possible to disable the warning when it is within a certain call, like Assert.AreEqual?
Since this is an issue with a lot of unit tests, I don't want to litter the tests with the ReSharper disable code.
Right now the only option I can think of is to change every Assert.IsNotNull call to be
var someObject = GetObject();
if(someObject == null)
{
Assert.Fail("someObject is null");
return;
}
Although this kind of seems to defeat the purpose of having Assert.IsNotNull in the first place. Just wondering if there is a better way.
I don't know the specific library you use, but I'd try something like
Assert.IsTrue(someObject != null);
or, for the sake of completeness,
Assert.IsNotNull(someObject, "someObject must not be null");
Assert.IsNotNull(someObject.SomeProperty, "SomeProperty must not be null either");
Assert.SomethingElse(...);
Add this to your project:
public static class AssertionsExtensions
{
[NotNull]
public static TSubject ShouldNotBeNull<TSubject>([CanBeNull] this TSubject source,
[CanBeNull] string because = "", [CanBeNull] [ItemCanBeNull] params object[] reasonArgs)
{
source.Should().NotBeNull(because, reasonArgs);
// ReSharper disable once AssignNullToNotNullAttribute
return source;
}
}
Then use it like this, for example:
// Assert
succeeded.Should().Be(true, "<USB loopback cable must be connected and COM port must be correct.>");
DeviceStatus deviceStatusNotNull = testRunner.Result.ShouldNotBeNull();
deviceStatusNotNull.DeviceAddress.Should().Be(deviceAddress);
deviceStatusNotNull.IsInNetwork.Should().Be(true);
If I am not mistaken, your problem is that resharper gives warnings when null is not checked foreach object. You can modify resharper rules not to give null warnings in test classes.
Here is a link about changing ReSharper naming style for test methods.
Use NUnit instead of MBUnit. NUnit's implementation of Assert.IsNotNull() is picked up as guaranteeing not null whereas MBUnit's is not.
You can use R# external annotations to suppress the warnings (see http://grahamrhay.wordpress.com/2011/01/09/external-annotations/).
What version of MbUnit/Gallio are you using?
You can use ContractAnnotations to indicate the execution stops if parameter is null. See jetbrains contract annotations. Sample class:
public static class FluentExtensions
{
//see: https://www.jetbrains.com/help/resharper/2017.3/Contract_Annotations.html
[ContractAnnotation("null => stop")]
public static void ShouldNotBeNull(this object objToTest)
{
objToTest.Should().NotBeNull();
}
}
Usage:
doc.ShouldNotBeNull();
doc.Content.ShouldNotBeNull();
I have some factory method
public T Create<T> () where T : class
{
Contract.Ensures(Contract.Result<T>() != null);
T result = this.unityContainer.Resolve<T>();
return result;
}
The I try to build the project i get the warning:
CodeContracts: ensures unproven: Contract.Result() != null
I understand that IUnityContainer interface does not have any contracts so Code Contracts think that varible may be null and there is no way to prove that Create() will return not null result.
How in this case I can make Code Contracts belive that result variable is not null?
I first tried to call Contract.Assert
public T Create<T> () where T : class
{
Contract.Ensures(Contract.Result<T>() != null);
T result = this.unityContainer.Resolve<T>();
Contract.Assert(result != null);
return result;
}
But it takes me another warning:
CodeContracts: assert unproven
I tried make check for null and this makes all warnings gone:
public T Create<T> () where T : class
{
Contract.Ensures(Contract.Result<T>() != null);
T result = this.unityContainer.Resolve<T>();
if (result == null)
{
throw new InvalidOperationException();
}
return result;
}
But i'm not sure this is good solution to throw exception manually. May be there is some way to solve problem using Code Contracts only?
Thank you.
I think you want Contract.Assume:
Contract.Assume(result != null);
From the docs:
Instructs code analysis tools to assume that the specified condition is true, even if it cannot be statically proven to always be true.
This will still validate the result at execution time if you have the rewriter appropriately configured.
Like if((result ?? 0) == 0){}
To make this more clear (readable) you can define an extension method.
Edit
#allentracks answer is more precise for your question
I would like to prevent further processing on an object if it is null.
In the following code I check if the object is null by either:
if (!data.Equals(null))
and
if (data != null)
However, I receive a NullReferenceException at dataList.Add(data). If the object was null, it should never have even entered the if-statement!
Thus, I'm asking if this is proper way of checking if an object is null:
public List<Object> dataList;
public bool AddData(ref Object data)
bool success = false;
try
{
// I've also used "if (data != null)" which hasn't worked either
if (!data.Equals(null))
{
//NullReferenceException occurs here ...
dataList.Add(data);
success = doOtherStuff(data);
}
}
catch (Exception e)
{
throw new Exception(e.ToString());
}
return success;
}
If this is the proper way of checking if the object is null, what am I doing wrong (how can I prevent further processing on the object to avoid the NullReferenceException)?
It's not data that is null, but dataList.
You need to create one with
public List<Object> dataList = new List<Object>();
Even better: since it's a field, make it private. And if there's nothing preventing you, make it also readonly. Just good practice.
Aside
The correct way to check for nullity is if(data != null). This kind of check is ubiquitous for reference types; even Nullable<T> overrides the equality operator to be a more convenient way of expressing nullable.HasValue when checking for nullity.
If you do if(!data.Equals(null)) then you will get a NullReferenceException if data == null. Which is kind of comical since avoiding this exception was the goal in the first place.
You are also doing this:
catch (Exception e)
{
throw new Exception(e.ToString());
}
This is definitely not good. I can imagine that you put it there just so you can break into the debugger while still inside the method, in which case ignore this paragraph. Otherwise, don't catch exceptions for nothing. And if you do, rethrow them using just throw;.
in C# > 7 use if (obj is null)
For not null use:
C# 7-8: if (obj is object)
C# 9-: if (obj is not null)
These will ignore any == or != defined by the object (unless of course you want to use them for null checks)
For more, in the C# Language Reference, see is operator.
C# 6 has monadic null checking :)
before:
if (points != null) {
var next = points.FirstOrDefault();
if (next != null && next.X != null) return next.X;
}
return -1;
after:
var bestValue = points?.FirstOrDefault()?.X ?? -1;
Your dataList is null as it has not been instantiated, judging by the code you have posted.
Try:
public List<Object> dataList = new List<Object>();
public bool AddData(ref Object data)
bool success = false;
try
{
if (!data.Equals(null)) // I've also used if(data != null) which hasn't worked either
{
dataList.Add(data); //NullReferenceException occurs here
success = doOtherStuff(data);
}
}
catch (Exception e)
{
throw;
}
return success;
}
[Edited to reflect hint by #kelton52]
Simplest way is to do object.ReferenceEquals(null, data)
Since (null==data) is NOT guaranteed to work:
class Nully
{
public static bool operator ==(Nully n, object o)
{
Console.WriteLine("Comparing '" + n + "' with '" + o + "'");
return true;
}
public static bool operator !=(Nully n, object o) { return !(n==o); }
}
void Main()
{
var data = new Nully();
Console.WriteLine(null == data);
Console.WriteLine(object.ReferenceEquals(null, data));
}
Produces:
Comparing '' with 'Nully'
True
False
As of C# 9 you can do
if (obj is null) { ... }
For not null use
if (obj is not null) { ... }
If you need to override this behaviour use == and != accordingly.
No, you should be using !=. If data is actually null then your program will just crash with a NullReferenceException as a result of attempting to call the Equals method on null. Also realize that, if you specifically want to check for reference equality, you should use the Object.ReferenceEquals method as you never know how Equals has been implemented.
Your program is crashing because dataList is null as you never initialize it.
The problem in this case is not that data is null. It is that dataList itself is null.
In the place where you declare dataList you should create a new List object and assign it to the variable.
List<object> dataList = new List<object>();
With c#9 (2020) you can now check a parameter is null with this code:
if (name is null) { }
if (name is not null) { }
You can have more information here
As of C# 8 you can use the 'empty' property pattern (with pattern matching) to ensure an object is not null:
if (obj is { })
{
// 'obj' is not null here
}
This approach means "if the object references an instance of something" (i.e. it's not null).
You can think of this as the opposite of: if (obj is null).... which will return true when the object does not reference an instance of something.
For more info on patterns in C# 8.0 read here.
In addition to #Jose Ortega answer,
its better for use extension method
public static bool IsNull(this object T)
{
return T == null;
}
And use IsNull method for all of object like:
object foo = new object(); //or any object from any class
if (foo.IsNull())
{
// blah blah //
}
Jeffrey L Whitledge is right. Your `dataList´-Object itself is null.
There is also another problem with your code: You are using the ref-keyword, which means the argument data cannot be null! The MSDN says:
An argument passed to a ref parameter must first be initialized. This differs from out, whose arguments do not have to be explicitly initialized before they are passed
It's also not a good idea to use generics with the type `Object´. Generics should avoid boxing/unboxing and also ensure type safety. If you want a common type make your method generic. Finally your code should look like this:
public class Foo<T> where T : MyTypeOrInterface {
public List<T> dataList = new List<T>();
public bool AddData(ref T data) {
bool success = false;
try {
dataList.Add(data);
success = doOtherStuff(data);
} catch (Exception e) {
throw new Exception(e.ToString());
}
return success;
}
private bool doOtherStuff(T data) {
//...
}
}
As others have already pointed out, it's not data but rather likely dataList that is null. In addition to that...
catch-throw is an antipattern that almost always makes me want to throw up every time that I see it. Imagine that something goes wrong deep in something that doOtherStuff() calls. All you get back is an Exception object, thrown at the throw in AddData(). No stack trace, no call information, no state, nothing at all to indicate the real source of the problem, unless you go in and switch your debugger to break on exception thrown rather than exception unhandled. If you are catching an exception and just re-throwing it in any way, particularly if the code in the try block is in any way nontrivial, do yourself (and your colleagues, present and future) a favor and throw out the entire try-catch block. Granted, throw; is better than the alternatives, but you are still giving yourself (or whoever else is trying to fix a bug in the code) completely unnecessary headaches. This is not to say that try-catch-throw is necessarily evil per se, as long as you do something relevant with the exception object that was thrown inside the catch block.
Then there's the potential problems of catching Exception in the first place, but that's another matter, particularly since in this particular case you throw an exception.
Another thing that strikes me as more than a little dangerous is that data could potentially change value during the execution of the function, since you are passing by reference. So the null check might pass but before the code gets to doing anything with the value, it's changed - perhaps to null. I'm not positive if this is a concern or not (it might not be), but it seems worth watching out for.
public static bool isnull(object T)
{
return T == null ? true : false;
}
use:
isnull(object.check.it)
Conditional use:
isnull(object.check.it) ? DoWhenItsTrue : DoWhenItsFalse;
Update (another way) updated 08/31/2017 and 01/25/2021. Thanks for the comment.
public static bool IsNull(object T)
{
return (bool)T ? true : false;
}
Demostration
And for the records, you have my code on Github, go check it out:
https://github.com/j0rt3g4/ValidateNull
PS: This one is especially for you Chayim Friedman, don't use beta software assuming that is all true. Wait for final versions or use your own environment to test, before assuming true beta software without any sort of documentation or demonstration from your end.
Whenever you are creating objects of class you have to check the whether the object is null or not using the below code.
Example:
object1 is object of class
void myFunction(object1)
{
if(object1!=null)
{
object1.value1 //If we miss the null check then here we get the Null Reference exception
}
}
There is a one-liner in .NET 6
ExampleMethod(null);
void ExampleMethod(object param)
{
ArgumentNullException.ThrowIfNull(param);
// Do something
}
I just followed a method that we would usually follow in java script. To convert object to string and then check whether they are null.
var obj = new Object();
var objStr = obj.ToString();
if (!string.IsNullOrEmpty(objStr)){
// code as per your needs
}
I did more simple (positive way) and it seems to work well.
Since any kind of "object" is at least an object
if (MyObj is Object)
{
//Do something .... for example:
if (MyObj is Button)
MyObj.Enabled = true;
}
You can try like below
public List<Object> dataList;
public bool AddData(ref Object data)
bool success = false;
try
{
if (data != null)
{
dataList.Add(data);
success = doOtherStuff(data);
}
}
catch (Exception e)
{
throw new Exception(e.ToString());
}
return success;
}
Here are some extensions I use:
/// <summary>
/// Extensions to the object class
/// </summary>
public static class ObjectExtensions
{
/// <summary>
/// True if the object is null, else false
/// </summary>
public static bool IsNull(this object input) => input is null;
/// <summary>
/// False if the object is null, else true
/// </summary>
public static bool NotNull(this object input) => !IsNull(input);
}
public bool IsVisible(object ClaimCount)
{
bool flag = true;
#region || HIDE COLUMNS ON CONDITION BASIS
if (!String.IsNullOrEmpty(Convert.ToString(ClaimCount)))
{
Int32 ClaimCnt = Convert.ToInt32(ClaimCount);
if (ClaimCnt == 1)
{
flag = false;
}
}
#endregion
return flag;
}
Okay, I have yet another Code Contracts question. I have a contract on an interface method that looks like this (other methods omitted for clarity):
[ContractClassFor(typeof(IUnboundTagGroup))]
public abstract class ContractForIUnboundTagGroup : IUnboundTagGroup
{
public IUnboundTagGroup[] GetAllGroups()
{
Contract.Ensures(Contract.Result<IUnboundTagGroup[]>() != null);
Contract.Ensures(Contract.ForAll(Contract.Result<IUnboundTagGroup[]>(), g => g != null));
return null;
}
}
I have code consuming the interface that looks like this:
public void AddRequested(IUnboundTagGroup group)
{
foreach (IUnboundTagGroup subGroup in group.GetAllGroups())
{
AddRequested(subGroup);
}
//Other stuff omitted
}
AddRequested requires a non-null input parameter (it implements an interface which has a Requires contract) and so I get a 'requires unproven: group != null' error on the subGroup being passed into AddRequested. Am I using the ForAll syntax correctly? If so and the solver simply isn't understanding, is there another way to help the solver recognize the contract or do I simply need to use an Assume whenever GetAllGroups() is called?
The Code Contracts User Manual states, "The static contract checker does not yet deal with quantiers ForAll or Exists." Until it does, it seems to me the options are:
Ignore the warning.
Add Contract.Assume(subGroup != null) before the call to AddRequested().
Add a check before the call to AddRequested(). Maybe if (subGroup
== null) throw new InvalidOperationException() or if (subGroup != null)
AddRequested(subGroup).
Option 1 doesn't really help. Option 2 is risky because it will circumvent the AddRequested() Requires contract even if IUnboundTagGroup.GetAllGroups() no longer ensures that post-condition. I'd go with option 3.