9

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 get an error.

After some research I found out that one can use a reserved keyword as a property or variable name by adding a @ prefix in C#, or by enclosing it in square brackets [] in VB.NET. For example:

var @class = new object();

So here is my class design code.

public class Person
{
    string _retVal;

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

...
Person p = new Person();
p.@return = "hello";

Now I am not getting any error, but when I try to access property name like return then I need to write the name like @return, which I don't want. I want to access the property name like p.return = "hello"; instead of p.@return = "hello"; so I'd like to know if there is any way to do that?

stakx - no longer contributing
  • 83,039
  • 20
  • 168
  • 268
Thomas
  • 33,544
  • 126
  • 357
  • 626
  • 10
    Why bent on using reserved Keyword? – Nikhil Agrawal Jun 06 '12 at 10:45
  • 3
    doesn't seem reasonable to me. You could use a "Return" name instead which is not a reserved keyword. – Andrey Ermakov Jun 06 '12 at 10:46
  • 1
    use `result` instead of `return`. Variable choice is your freedom. – ebattulga Jun 06 '12 at 10:48
  • 1
    There is a way to do this in C# using dynamic dispatch, however it would be over-complicating things to such a degree that I'd actually feel bad for suggesting it.. – MattDavey Jun 06 '12 at 11:06
  • 1
    @phg I'm not certain but I think if you changed the property to `Return` you would also need to flag the assembly as *non* CLS compliant.. – MattDavey Jun 06 '12 at 11:10
  • @MattDavey I agree, and I wouldn't call it `Return` myself if I worked on a library. But if it's just some small c# program which won't ever be called by anything else, and one insists on `Return`, who cares. Still, good point. – phipsgabler Jun 06 '12 at 11:20

3 Answers3

31

You can't. It is a reserved keyword. That means "you can't". Contrast to "contextual keywords" which usually means "we added this later, so we needed it to work in some pre-existing scenarios".

The moderate answer here is: use @return.

A better answer here is: rename your property. Perhaps ReturnValue.

There is also the option of, say, Return - but you might need to think about case-insensitive languages too.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
-1

You can rename namespaces like this:

using Test = System.Diagnostics;
Praveen Patel G
  • 342
  • 4
  • 13
-3

No way to achieve this because reserved Keywords are predefined, reserved identifiers that have special meanings to the compiler.

it's better you change name of property and use it in you code...something as given in @Marc answer...

Pranay Rana
  • 175,020
  • 35
  • 237
  • 263