String or StringBuilder return values?

前端 未结 5 1768
生来不讨喜
生来不讨喜 2021-02-12 19:06

If I am building a string using a StringBuilder object in a method, would it make sense to:

Return the StringBuilder object, and let the calling code call ToString()?

5条回答
  •  庸人自扰
    2021-02-12 19:34

    I don't think performance should be a factor in this question. Either way someone is going to call sb.ToString() so your going to take the hit someplace.

    The more important question is what is the intention of the method and the purpose. If this method is part of a builder you might return the string builder. Otherwise I would return a string.

    If this is part of a public API I would lean towards returning a string instead of the builder.

提交回复
热议问题