tags:

views:

77

answers:

3

Hi, is it possible to use dash (-) in a member name of an anonymous class? I'm mainly interested in this to use with asp.net mvc to pass custom attributes to html-helpers, since I want my html to pass html5-validation, this starting with data-.

Exemple that doesn't work:

<%=Html.TextBoxFor(x => x.Something, new {data-animal = "pony"})%>

Putting a @ in front of the member name doesn't do the trick either.

Update: If this isn't possible, is there a recommended way todo what I want? My current temporary solution is to add a replace to the whole thing like this:

<%=Html.TextBoxFor(x => x.Something, new {data___animal = "pony"}).Replace("___", "-")%>

But that sucks, because it's ugly and will break when Model.Something contains three underscores. Buhu.

+2  A: 

No, because the dash is a C# operator (minus), and white space isn't significant.

Right now the compiler thinks you are trying to subtract animal from data, which doesn't work unless the - operator is specified for the types in question.

Mark Seemann
+3  A: 

It is not possible to use - as part of any identifier. http://msdn.microsoft.com/en-us/library/aa664670(VS.71).aspx

Andrey
A: 

No, you can't use the hyphen character. You need to use alphanumeric characters, underscores, or the other characters described here. '-' is treated as a minus. data-animal would be treated the same as data - animal, so that won't even compile unless you have separately defined data and animal (and it could present subtle bugs if you have!).

Edit: With C#'s capability to have identifiers with Unicode escape sequences, you can get the effect of a dash in an identifier name. The escape sequence for "&mdash" (the longer dash character) is "U+2014". So you would express data-animal as data\u2014animal. But from a coding style point of view, I'm not sure why you wouldn't choose a more convenient naming convention.

Also, another point to highlight from "2.4.2 Identifiers (C#)": You can't have two of these escape sequences back to back in an identifier (e.g. data\u2014\u2014animal).

David
The naming convention is from HTML5; http://dev.w3.org/html5/spec/dom.html#embedding-custom-non-visible-data
svinto
Ps yeah, \u2014 is like eh not optimal.
svinto
David
@svinto: You're right, \u2014 is not optimal. I was just pointing out that you can in fact use it in an identifier if you want the dash character. That said, even if you did have a way to make these \u* identifiers more human-readable, they would look the same as the characters ('-', etc.) that aren't allowed in identifiers (unless the syntax was highlighted differently, but admittedly I am not well-versed in that).
David