简体   繁体   中英

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, ie F#, it would just be params . In fact, in C#, if you write @x it's exactly equivalent to x .

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();
        }
    }
}

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM