Skip to content

[API Proposal]: string.ConstantEmpty #60508

Closed

Description

@deeprobin

Background and motivation

string.Empty is a static readonly empty string. Since this cannot be used in attributes, I would like to suggest that we create a constant version of this.

API Proposal

namespace System
{
    public sealed class String : ICloneable, IComparable, IComparable<string>, IConvertible, IEquatable<string>, System.Collections.Generic.IEnumerable<char>
    {
        // Current:
        public static readonly string Empty = "";

        // Proposal:
        // Naming could also be "ConstEmpty" instead of "ConstantEmpty"
        public const string ConstantEmpty = "";
    }
}

API Usage

[Theory]
[InlineData(string.ConstEmpty)]
// previous: [InlineData("")]
public void MyTest(input) {
    Assert.True(string.IsNullOrEmpty(input));
}

Alternative Designs

No response

Risks

No risks, since only a constant is applied and does not replace the static field.

Activity

  1. added
    api-suggestion
    on Oct 16, 2021
  2. ghost added
    untriaged
    on Oct 16, 2021
  3. stephentoub commented on Oct 16, 2021

    @stephentoub
    Member

    Why not just use ""? Why is a new const better?

  4. deeprobin commented on Oct 16, 2021

    @deeprobin
    ContributorAuthor

    Why not just use ""? Why is a new const better?

    Well I used to prefer string.Empty to "" most of the time (but that does not work in Attributes). Although the static call is not much slower performance-wise.

  5. teo-tsirpanis commented on Oct 17, 2021

    @teo-tsirpanis
    Contributor

    Although the static call is not much slower performance-wise.

    The static call will almost surely be optimized away. Returning "" generates the exact same assembly code as returning string.Empty. Also the IL instructions ldstr "" and ldsfld String.Empty take the same amount of space.

    I persume you want to add this constant field to completely avoid writing "" in your code, based on the knowledge that magic strings are a bad practice. But the empty string is not a magic string per se, you could view its two consecutive double quotes as a symbol like || or &&.

  6. danmoseley commented on Oct 17, 2021

    @danmoseley
    Contributor

    @deeprobin thanks for the proposal but the consensus seems to be that “” is sufficient and arguably more readable as well.

  7. ghost locked as resolved and limited conversation to collaborators on Nov 16, 2021
  8. removed
    untriaged
    on Jun 24, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionarea-System.Runtime

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions