Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 887
Jack Thor Avatar asked Jan 10 '18 19:01

Jack Thor


2 Answers

You just need to use a format string in the interpolated value to force the result to integer format.

Dim sDateModified As String 
sDateModified = $"<div name='commenttype{CommentType.MyComment:D}'></div>"
like image 95
Theo Brinkman Avatar answered Oct 22 '22 04:10

Theo Brinkman


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)
like image 35
Nate Barbettini Avatar answered Oct 22 '22 04:10

Nate Barbettini