Friday 5 April 2013

CSharp: setting private field reflection

Question:
How can I set the StackTrace property of an exception in c#?
Can I set a private field of an object in dot.net?


Answer:
You cannot set the property "StackTrace" of the exception class but you can set a private field called "_stackTraceString" using reflection.
When you inspect the Exception class (with IlSpy an open-source .NET assembly browser and decompiler) you'll see that the StackTrace property will return the _stackTraceString if it is set.

Here is an example
string msg = "no problemo";
string stackTrace = "--- stack trace from somewhere else ---";

Exception ex = new Exception(msg);
FieldInfo fInfo = typeof(Exception).GetField("_stackTraceString", BindingFlags.Instance | BindingFlags.NonPublic);
fInfo.SetValue(ex, stackTrace);








No comments: