Check if Action input parameter is null - c#

I have a method with the signature below. I put in checks to make sure that the inputs are not null. However, with input parameters that are an Action it is always seeing the input as null. What is a better way to perform this check for inputs that are of Action Type?
Any suggestions would be appreciated.
public void DeleteTreeValue(TreeValue treeValue, Action<Exception> callback)
{
if (treeValue == null)
throw new ArgumentNullException("treeValue");
//This is always throwing the ArugmentNullException even when the callback is passed
if (callback == null)
throw new ArgumentNullException("callback");
EDIT: Here is an example of how it is being called. I can see the method in the call back when I debug it, but this could still be seen as null in the arg check which is probably what is happening.
[Test]
public void DeleteValueShouldThowExceptionWhenValueDoesNotExist()
{
var myValue = new TreeValue {TreeValueId = -1};
_dataService.DeleteTreeValue(myValue, exception =>
{
Assert.IsNotNull(exception);
});
}

Related

How to verify method was reached if throw before

I have my method as below which adds new user to database when such user name doesn't exist in database. If user name exist it throws custom exception therefore addUserType method is not reached.
public void CreateUserType(UserType userType)
{
if (userType == null) throw new ApplicationException("UserType object cannot be null");
if (_bottleClientQuery.IsUserTypeExist(userType.Name)) throw new ApplicationException("Such user type name already exist");
_bottleClientRepository.AddUserType(userType);
}
My testing methods are as shown below:
This method correctly giving me the expected result:
[Test]
public void CreateUserType_UserTypeExists_ThrowsApplicationException()
{
UserQuery.Setup(uow => uow.IsUserTypeExist(It.IsAny<string>())).Returns(true);
Assert.Throws<Exceptions.ApplicationException>(() => CreateClientService.CreateUserType(new UserType()));
}
Nevertheless in this method i want to check whether AddUserType was reached or not. I setup it as IsUserTypeExist returns true which means such user name exist therefore
AddUserType will be not reached.
[Test]
public void CreateUserType_UserTypeExists_AddUserTypeRepositoryNotReached()
{
UserQuery.Setup(uow => uow.IsUserTypeExist(It.IsAny<string>())).Returns(true);
CreateClientService.CreateUserType(new UserType());
UserRepository.Verify(uow => uow.AddUserType(It.IsAny<UserType>()),Times.Never);
}
The problem with second test method is the ApplicationException is thrown (that's fully fine and expected) but i would really like to test whether AddUserType was not reached.
Is it possible when before thrown exception was there?
You could change your test method to something like this;
[Test]
public void CreateUserType_UserTypeExists_AddUserTypeRepositoryNotReached()
{
UserQuery.Setup(uow => uow.IsUserTypeExist(It.IsAny<string>())).Returns(true);
Assert.Throws<ApplicationException>(() => CreateClientService.CreateUserType(new UserType()));
UserRepository.Verify(uow => uow.AddUserType(It.IsAny<UserType>()),Times.Never);
}
This will both verify that the expected exception is thrown and ensure that execution continues to your next verification.

Trivial exit from an method that may perform an asynchronous call

I've got an issue calling a method that may return a Task<T> or null depending on the result of an initial synchronous lookup call (this itself might be an anti-pattern so please let me know).
I kind of want to return null if a trivial exit condition occurs but this is causing the calling (outer) method to fail because the outer call expects a Task<T> response (trivial exit) which gets pushed through to ConfigureAwait(true) which subsequently produces a NullReferenceException.
Outer calling method:
var res = await MyService.GetUserCourseStatusAsync(userID, productID).ConfigureAwait(true);
Intermediate method:
public Task<IGetUserCourseResponse> GetUserCourseStatusAsync(int userID, int productID)
{
// Look up User's ID (if exists)
var userCredentials = GetUserCredentials(userID);
if (userCredentials?.UserID == null)
return null; // Trivial return of null ("User not registered"). *** This causes exception on ConfigureAwait(true) above ***
// Another synchronous call
var courseId = GetCourseID(productID);
if (courseId == null)
throw new InvalidOperationException($"Product #{productID} is not a course");
// Asynchronous call to inner method (this bit works fine)
return GetUserCourseAsync(userCredentials.UserID.Value, courseId.Value);
}
So my thought then is that we should always return a Task<T> instead of null.
However, all of these cause compile errors:
//return null; // Trivial return of null ("User not registered"). *** This causes exception
// Compile error: CS0029: Cannot implicitly convert type 'GetUserCourseInner' to 'System.Threading.Tasks.Task<IGetUserCourseResponse>'
return new GetUserCourseInner(); // Not registered
// Compile error: CS1503 Argument 1: cannot convert from 'GetUserCourseInner' to 'System.Func<IGetUserCourseResponse>'
return new Task<IGetUserCourseResponse>(new GetUserCourseInner()); // Not registered
How do I return a dummy Task<T> that isn't a result of a async call?
Is this even the correct approach?
It would be better, as you suggested, to return a Task<IGetUserCourseResponse> which contains null (or some other sentinel value). You can create such a completed Task with Task.FromResult((IGetUserCourseResponse)null):
public Task<IGetUserCourseResponse> GetUserCourseStatusAsync(int userID, int productID)
{
// Look up User's ID (if exists)
var userCredentials = GetUserCredentials(userID);
if (userCredentials?.UserID == null)
return Task.FromResult((IGetUserCourseResponse)null);
// Another synchronous call
var courseId = GetCourseID(productID);
if (courseId == null)
throw new InvalidOperationException($"Product #{productID} is not a course");
// Asynchronous call to inner method (this bit works fine)
return GetUserCourseAsync(userCredentials.UserID.Value, courseId.Value);
}
Alternatively, you could make your outer method async. Note however that this changes its behaviour in the case where it throws an InvalidOperationException: instead of the method throwing this exception directly, it will instead return a Task which contains this exception. This may or may not be what you want:
public async Task<IGetUserCourseResponse> GetUserCourseStatusAsync(int userID, int productID)
{
// Look up User's ID (if exists)
var userCredentials = GetUserCredentials(userID);
if (userCredentials?.UserID == null)
return null;
// Another synchronous call
var courseId = GetCourseID(productID);
if (courseId == null)
throw new InvalidOperationException($"Product #{productID} is not a course");
// Asynchronous call to inner method (this bit works fine)
return await GetUserCourseAsync(userCredentials.UserID.Value, courseId.Value);
}
Just return a Task that holds a null value as result
return Task.FromResult<IGetUserCourseResponse>(null);

How does a lambda expression working in the given code snippet

I have the below code snippet in my project. I am new to lambda expressions. I have some idea about it and also
started using it. But I do not understand how the below code is working. Specially,
NotifyIntrenal( notification, callback, changedTypes => ..
Now here changedTypes is one of the parameter for method NotifyIntrenal. We derive its value using an anomymous method.
If I see the code, since I do not assign any value to changedTypes, so as per my understanding the code if (changedTypes == null) should
always be true. But this is not the case when I debug.
Can someone explain me how does this works here?
private void Notify( Notification notification )
{
var nameDto = GetNameDto();
foreach (var subscription in _subscriptionsDictionary)
{
var callback = subscription.Key;
var subscribedTypes = subscription.Value;
NotifyIntrenal( notification, callback, changedTypes =>
{
if (changedTypes == null)
return subscribedTypes;
if (!changedTypes.Any())
return subscribedTypes;
return changedTypes.Intersect(subscribedTypes);
}, nameDto);
}
}
Thanks & Regards
changedTypes is not an argument to NotifyInternal. It is the parameter for the anonymous method.
This whole method is the argument for NotifyInternal.
The code inside that lambda is not executed at this point. It will only be executed if some line in NotifyInternal calls it. So there has to be code line in NotifyInternal executing the anonymous method:
void NotifyInternal(Notification notification, Callback callback, Func<IEnumerable<Type>, IEnumerable<Type>> function, string nameDto)
{
// ... some code
// execute the lambda
var result = function(mychangedtypesvariable);
// ... more code
}
Only then the code inside the lambda is executed, using the pass argument (mychangedtypesvariable in that example). So if this will be null you cannot decide from the snippet you see.
changedTypes is just a paremeter for your anonymous method, not for NotifyIntrenal. The latter however calls that anonymous method and fills the parameter (if required) appropriately. In your case the anonymous method expects an IEnumerable<MyType> and returns an IEnumerable<MyType>.
NotifyIntrenal(string arg1, string arg2, Func<IEnumerable<MyType>, IEnumerable<MyType>> func) {
// do something
var list = new List<MyType> { ...}
// execute the delegate with the list
IEnumerable<MyType> result = func(list);
}
So actually changedTypes is provided by NotifyIntrenal, not given to it. How you create that argument within the method is up to you.

Explanation of success/failure terms with C# Actions?

I found the method below in a Windows Phone 7 C# sample. In it you can see the terms success and failure used inside the method. I tried Go To Definition with either term and Visual Studio did not jump to a definition for either term. I tried searching Google using the terms "Action", "success", "failure", "C#", and "parameter" and did not find anything useful. Are success and failure in this context macros or something similar? Where can I get an explanation of what they do and how to use them? Note, the tooltip help when hovered over failure shows "parameter Action<string> failure".
public void SendAsync(string userName, string message, Action success, Action<string> failure)
{
if (socket.Connected) {
var formattedMessage = string.Format("{0};{1};{2};{3};{4}",
SocketCommands.TEXT, this.DeviceNameAndId, userName, message, DateTime.Now);
var buffer = Encoding.UTF8.GetBytes(formattedMessage);
var args = new SocketAsyncEventArgs();
args.RemoteEndPoint = this.IPEndPoint;
args.SetBuffer(buffer, 0, buffer.Length);
args.Completed += (__, e) => {
Deployment.Current.Dispatcher.BeginInvoke(() => {
if (e.SocketError != SocketError.Success) {
failure("Your message can't be sent.");
}
else {
success();
}
});
};
socket.SendAsync(args);
}
}
They are delegates that are being used as "callback functions". Basically, they are functions that are provided to another function that can be called inside that function. Perhaps a smaller sample would make more sense:
static void PerformCheck(bool logic, Action ifTrue, Action ifFalse)
{
if (logic)
ifTrue(); // if logic is true, call the ifTrue delegate
else
ifFalse(); // if logic is false, call the ifFalse delegate
}
False is printed in the below example, because 1 == 2 evaluates to false. So, logic is false within the PerformCheck method.. so it calls the ifFalse delegate. As you can see, ifFalse prints to the Console:
PerformCheck(1 == 2,
ifTrue: () => Console.WriteLine("Yep, its true"),
ifFalse: () => Console.WriteLine("Nope. False."));
Whereas this one will print true.. because 1 == 1 evaluates to true. So it calls ifTrue:
PerformCheck(1 == 1,
ifTrue: () => Console.WriteLine("Yep, its true"),
ifFalse: () => Console.WriteLine("Nope. False."));
You can think of Action (and also Func) as variables that hold other methods.
You can pass, assign and basically do anything to an Action that you would any other variable, but you can also call it like a method.
Say you have two methods in your code:
public void Main(){
Action doWork;
doWork = WorkMethod;
doWork();
}
private void WorkMethod(){
//do something here
}
You assign WorkMethod to the action like you would do any assignment to the variable. Then, you can call doWork as though it were a method. It isn't particularly useful in this example, but you can probably see how all the benefits of standard variables apply.
You use an Action and a Func in pretty much the same way. The only real difference is that an Action represents a void and a Func requires a return type.
You can also use generics. For example Action<int> respresents a method with the signature
void methodName(int arg){}
Action<int, string> would be
void methodName(int arg1, string arg2){}
Func is similar, Func<int> would be:
int methodName(){}
Func<string, int> would be:
int methodName(string arg){}
It's important to remember that the last type in the Func definition is the return type, even though it appears first in the actual method signature.

Checking if an object is null in C#

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;
}

Categories