"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to use C# keywords as attribute names in ASP.NET MVC view

How to use C# keywords as attribute names in ASP.NET MVC view

Posted on 2025-04-18
Browse:139

How Can I Use C# Keywords as Property Names in ASP.NET MVC Views?

Use keywords as attribute names in C#

In ASP.NET MVC, you may want to use the C# keyword as the attribute name in the view. For example, consider the following code:

// 此代码无法编译,因为 "class" 是 C# 中的关键字。

This code cannot be compiled because "class" is a keyword in C#. To solve this problem, you can use it as an identifier by adding an @ symbol before the keyword.

// 通过添加@符号,可以成功编译。

According to MSDN's documentation on C# keywords:

"Keywords are predefined reserved identifiers that have special meanings for the compiler. They cannot be used as identifiers in the program unless the @ symbol is prefixed before the keyword."

So by using the @ prefix, the attribute name can be escaped and allowed to compile.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3