0

i.e. If you use this, it can trigger Object reference not set to an instance of an object:

try 
{
  Dictionary<int,int> ZZZ; 
  ZZZ[1]= ..;
}
catch(Exception e)
{    
    var stackTrace = new StackTrace(e);
    var frames = stackTrace.GetFrames();
    var method = frames[0].GetMethod(); 
    Console.WriteLine(method.Name);
}

However with StackTrace we can get the name of method, where this error happens.

But, how we can get the name of property which triggered error? In other languages like php, there is way to find (using debug_backtrace) the method which happened last time.

Is there anything similar, so it can find that last time was called i.e. set_ZZZ() (autosetter) method, or if it can directly say that ZZZ property caused issue?

T.Todua
  • 53,146
  • 19
  • 236
  • 237
  • 1
    You only can get the line of code whose responsible for error only in Debug mode not in release mode. – nAviD Jul 12 '19 at 21:36
  • @nAviD ok, and in debug mode, how to see line number ? tried `.GetILOffset()` etc, but none of them catches correctly. WHy cant reflection detect that last method happened was `set_ZZZ()` ? – T.Todua Jul 12 '19 at 21:49
  • You might be interested in this documentation page: https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.stacktrace?view=netframework-4.8 – M.Hazara Jul 12 '19 at 22:11
  • 1
    Try `new StackTrace(e, true)` to get the line number. Based on that code sample, reflection can't tell you that the last method was `set_ZZZ` because no such method is ever called. There is no `ZZZ` property, just a variable local to the `try` block. – Joshua Robinson Jul 12 '19 at 22:21
  • @JoshuaRobinson is that was private variable (instead of local), then wouldnt it trigger autosetter (`set_ZZZ`) method? – T.Todua Jul 13 '19 at 06:48
  • @T.Todua I'm sorry, I'm not sure what you mean. If you're asking if `ZZZ` were actually a property on some class, and you tried to set it on a `null` instance of that class then `set_ZZZ` would not be in the stack trace. `set_ZZZ` cannot be called on a `null`, so execution will never enter the generated set method. – Joshua Robinson Jul 15 '19 at 14:28

0 Answers0