Robert Fraser
Robert Fraser

Reputation: 10927

Use of @keyword in C# -- bad idea?

In my naming convention, I use _name for private member variables. I noticed that if I auto-generate a constructor with ReSharper, if the member is a keyword, it will generate an escaped keyword. For example:

class IntrinsicFunctionCall
{
    private Parameter[] _params;
    public IntrinsicFunctionCall(Parameter[] @params)
    {
        _params = @params;
    }
}

Is this generally considered bad practice or is it OK? It happens quite frequently with @params and @interface.

EDIT: This doesn't actually add a prefix to the variable name. If accessing that variable from a different .NET language, i.e. F#, it would just be params. In fact, in C#, if you write @x it's exactly equivalent to x.

Upvotes: 3

Views: 844

Answers (3)

Oliver Abraham
Oliver Abraham

Reputation: 73

Not generally bad practise. If you prefer to use prefixes for some kind of variables, it's ok. As far as I know, Microsoft recommends not to use prefixes, besides the I on interface names.

Upvotes: 0

Anonymous
Anonymous

Reputation: 9648

It's depend on your personal taste, however you need to keep your style consistent for all of your code.

This is sample of code consistency, use same style along the way.

int @number;
string @name;

This may consider a bad code, use mix style.

int @number;
string _name;

Upvotes: 0

Franci Penov
Franci Penov

Reputation: 76001

Using language keywords as identifiers impacts the readability. Granted, proper syntax high-lightning helps a bit, but it's better to not rely on the editor features only.

Consider the following (exaggeratedly unreadable, obviously :-)) code:

interface IInterfaceFactory<T>
{
   T CreateInstance(params object[] @params);
}

class SomeClass
{
    IMyOtherInterface _interface;

    public IMyOtherInterface Interface
    {
        get { return _interface; }
    }

    public SomeClass(params object[] @params)
    {
        SomeInterface<IMyOtherInterface> interfaceFactory = new SomeInterface<IMyOtherInterface>();
        IMyOtherInterface @interface = interfaceFactory.CreateInstance(@params);
        if (@interface->IsValid())
        {
            _interface = @interface;
        }
        else
        {
            _interface = interfaceFactory.CreateInstance();
        }
    }
}

Upvotes: 6

Related Questions