Search code examples
vb.netenumsstring-interpolation

String interpolation outputs enum name instead of value


I was hoping someone can explain this default functionality regarding string interpolation and the enum type.

I have this enum:

public enum CommentType
{
    MyComment = 24,
    TheirComment = 25,
    AnotherComment = 26
}

I am using it in a string:

Dim sDateModified As String 
sDateModified = $"<div name='commenttype{CommentType.MyComment}'></div>"

I was expecting CommentType.MyComment to be evaluated and the int value 24 to be used. The result should be: <div name='commenttype24'></div>

But what actually happens is that the identifier is used instead, giving me: <div name='commenttypeMyComment'></div>

In order to get the enum value I had to convert it to an integer:

sDateModified = $"<div name='commenttype{Convert.ToInt32(CommentType.MyComment)}'></div>"

It just feels counter intuitive to me. Can someone explain or point me to documentation on why it works this way?


Solution

  • You're getting the string value MyComment because that's what is returned by:

    CommentType.MyComment.ToString()
    

    Methods like String.Format and Console.WriteLine will automatically call ToString() on anything that isn't already a string. The string interpolation syntax $"" is just syntactic sugar for String.Format, which is why string interpolation also behaves this way.

    Your workaround is correct. For slightly more compact code, you could do:

    CInt(CommentType.MyComment)