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
source share
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
source

Why not just return the array? It is as simple as return new string[] { exError };

I don’t understand why people use a cannon to kill a fly, but you really don't need yield here ...

I should also note:

  • yield may not do what you expect

  • yield slower (not much, but there)

+4
source

To achieve this, you must use the return return statement.

 public static IEnumerable<string> GetMessage(Exception e) { yield return e.Message; } 
0
source

You can use yield return , as others have shown you, but I think this is a bit overkill, due to what happens behind the scenes.

Why don't you just create a List<String> with one element and return it? This is a IEnumerable<String> .

0
source

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
source

Source: https://habr.com/ru/post/1413373/


All Articles