How can I make a function return an IEnumerable <string> instead of a string in C #
I have the following function that returns a string:
public static string GetFormattedErrorMessage(this Exception e) { if (e == null) { throw new ArgumentNullException("e"); } var exError = e.Message; if (e.InnerException != null) { exError += "<br>" + e.InnerException.Message; if (e.InnerException.InnerException != null) { exError += "<br>" + e.InnerException.InnerException.Message; } } return exError; }
Can someone help and tell me how I can do this same function, return an IEnumerable<string>
just one element?
+4
5 answers
public static IEnumerable<string> GetFormattedErrorMessage(this Exception e) { if (e == null) { throw new ArgumentNullException("e"); } var exError = e.Message; if (e.InnerException != null) { exError += "<br>" + e.InnerException.Message; if (e.InnerException.InnerException != null) { exError += "<br>" + e.InnerException.InnerException.Message; } } yield return exError; }
+8
I see that you only need one element in IEnumerable, but I cannot understand why you want IEnumerable.
If you need every exception message and its internal exceptions, you must do the following:
public static IEnumerable<string> GetErrorMessages(this Exception e) { if (e == null) throw new ArgumentNullException("e"); yield return e.Message; Exception inner = e.InnerException; while(inner != null) { yield return inner.Message; inner = inner.InnerException; } }
0