From b48821bfa92b7b7b676a1ce9d4631cf8a6e788e5 Mon Sep 17 00:00:00 2001 From: Sebastien Pouliot Date: Wed, 4 Aug 2021 20:33:49 -0400 Subject: [PATCH] [foundation] Enable nullable for `MonoTouchException` and avoid potential `NullReferenceException` in some code paths. Also remove multiple string concatenations by using `StringBuilder` --- src/Foundation/MonoTouchException.cs | 43 ++++++++++++++++------------ 1 file changed, 24 insertions(+), 19 deletions(-) diff --git a/src/Foundation/MonoTouchException.cs b/src/Foundation/MonoTouchException.cs index c182c40b73af..9d695e02c906 100644 --- a/src/Foundation/MonoTouchException.cs +++ b/src/Foundation/MonoTouchException.cs @@ -1,10 +1,13 @@ #if !MONOMAC using System; +using System.Text; + +#nullable enable namespace Foundation { public class MonoTouchException : Exception { - private NSException native_exc; + NSException? native_exc; public MonoTouchException () : base () { native_exc = new NSException ("default", String.Empty, null); @@ -14,49 +17,51 @@ public MonoTouchException (NSException exc) : base () { native_exc = exc; } - public NSException NSException { + public NSException? NSException { get { return native_exc; } } - public string Reason { + public string? Reason { get { - return native_exc.Reason; + return native_exc?.Reason; } } - public string Name { + public string? Name { get { - return native_exc.Name; + return native_exc?.Name; } } public override string Message { get { - return string.Format ("Objective-C exception thrown. Name: {0} Reason: {1}\nNative stack trace:\n{2}", Name, Reason, NativeStackTrace); + var sb = new StringBuilder ("Objective-C exception thrown. Name: ").Append (Name); + sb.Append (" Reason: ").AppendLine (Reason); + sb.AppendLine ("Native stack trace:"); + AppendNativeStackTrace (sb); + return sb.ToString (); } } - string NativeStackTrace { - get { - var symbols = native_exc.CallStackSymbols; - var msg = string.Empty; - for (int i = 0; i < symbols.Length; i++) { - msg += "\t" + symbols [i] + "\n"; - } - return msg; + void AppendNativeStackTrace (StringBuilder sb) + { + if (native_exc is not null) { + foreach (var symbol in native_exc.CallStackSymbols) + sb.Append ('\t').AppendLine (symbol); } } public override string ToString () { var msg = base.ToString (); + if (native_exc is null) + return msg; - if (native_exc != null) - msg += NativeStackTrace; - - return msg; + var sb = new StringBuilder (msg); + AppendNativeStackTrace (sb); + return sb.ToString (); } } }