How do I know the log the last property that is null?
For example,
var a = "somevalue";
......
......
if(a == null)
{
Log.Error(MethodBase.GetCurrentMethod().Name + "Property : a is null");
//blah blah
}
Like how I use the reflection to get the current method name, there should be some means by which I can log the latest local variables (or a property or fields)
that is being compared ? I use, log4net by the way to log the errors.
1) Is there any method to achieve this or should we manually log it?
2) Is there any custom method that prints the class -> MethodName -> Propertyname(or FieldName) that is null?
Thanks for your time in advance.
As mentioned by @fsimonazzi, “a” would be a local variable.
That being said there is still no way to examine the current compare operation as in MSIL there is no formal concept of an IF block – only conditional jumps.
If you wanted to get really crazy with the reflection, you may be able to find the current executing instruction and look around near that for a variable, but even then, you will not find the name – only a reference – as names are only used prior to compilation.
Either way, reflection is not going to help you here.
Instead, try using Exceptions – specifically ArgumentNullException. This body of code would become:
then, when you call the method, you can catch the exception and log it – no matter what it may be.
Tools like FxCop can help make sure that you are properly validating each parameter.
Properties are actually implemented as methods, so reflection could help you there. If, for example, you were validating in a property and wanted to log the position automatically, you could.
The .Net Framework 4.5 also brings with it a new attribute that can be used to replace the
MethodBase.GetCurrentMethod().Nameconstruct you are using to get the method name. See[CallerMemberNameAttribute][3].