Share via


How do I use a C# reserve keyword as a property name

Question

Wednesday, June 6, 2012 6:44 AM

according to situation i need to design a class where one property name has to be "return" but when i create a property name like "return" then i got error. so i search google to find the solution and i came to know that we can use reserve keyword as a property name or variable name just adding *@ sign in c#* and [] in vb.net. like

var @class = new object();

so here is my class design code.

namespace TestApps
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        Person p = new Person();
        p.@return = "hello";
    }
}

public class Person
{
    string _retVal;

    public string @return
    {
        get { return _retVal; }
        set { _retVal = value; }
    }
} 
}

now i am not getting error but when i try to access property name like "return" then i need to write the name like @return which i dont want. i want to access the property name like p.return = "hello" instead of p.@return = "hello"; so like to know is there any way out that? please discuss. thanks

All replies (2)

Wednesday, June 6, 2012 6:57 AM ✅Answered

so like to know is there any way out that?

I usually name public properties with caps:

public class Person
{
    public string Return {get;set;}
}

That would avoid the problem since Return is not a keyword as C# is case-sensitive. 


Wednesday, June 6, 2012 11:34 AM ✅Answered

is there any way out that?

no, if you want to use a word that is the same as a c# keyword, you must use the @ prefix.

imho, to use a c# keyword even with the @ prefix is a very bad idea.

the idea behind OOP is to model the real world.

in your example, perhaps a property name like Reply or Response would be more meaningful.

http://msdn.microsoft.com/en-us/library/x53a06bb.aspx                "C# Keywords" vs2010
http://msdn.microsoft.com/en-us/library/x53a06bb(v=vs.110).aspx "C# Keywords" vs2012

also, i agree with Mike ( Mikesdotnetting) ... even though i'm mostly an iconoclast, the convention of using a capital letter for a public property is something that i find useful.

consider also, when you are choosing names, the likelihood that in some future version of c# your chosen variable name might become a c# keyword too.

g.