简体   繁体   中英

passing parameter that has the same name of class field variable in C#

With C++, I can make a code as follows.

class Terminal {
    int uid;

public:
    void SetUid(int uid) {self.uid = uid;}
};

I tried the similar thing in C#, but I got an error. I tried the following instead, but it looks ugly.

class Terminal {
    int uid;

public void SetUid(int uid_) {uid = uid_;}
}

What do you use when you want to pass a parameter that has the same name of class field variable in C#?

You can do this. Just use:

public void SetUid(int uid) { this.uid = uid; }
class Terminal {
    int uid;

    public void SetUid(int uid) { this.uid = uid; }
}

However, I would consider using a property instead:

class Terminal {
    public int Uid { get; set; }
}

Getter and setter methods usually smell of improper C# design, since properties give you the getter/setter mechanism wrapped into a nice bit of syntactic sugar.

In C++ it's not self , but this , and it's actually the same in C#;

 public void SetUid(int uid)
 {
    this.uid = uid;
 }

public void SetUid(int uid) {this.uid = uid;}

We don't name parameters the same as our fields, because it's confusing. Code gets read far more often than it gets written, so readability is paramount. Having to mentally decode which uid is the parameter, and which is the field, just isn't worth it.

We actually use an underscore prefix for our fields, to make it immediately obvious what's a field and what's a parameter / local. I know not everybody likes that convention, but we find it helpful.

In addition, for a SetXxx method like you're writing, we'll often just name the parameter value , following the convention of C# property setters. Since there's only the one parameter, and you already know what it means from the method name, "value" is just as meaningful as "uid".

So in our shop, your example would probably end up looking like this:

public class Terminal {
    private int _uid;

    public void SetUid(int value) {
        _uid = value;
    }
}

That's assuming that the uid is write-only. If it were read-write, of course we'd use a property instead of getter/setter methods.

I've started to get into the habit of prefixing parameters with "the", as in "theUID" or "the_uid" if you prefer underscores.

public void SetUID(int theUID) {
    uid = theUID;
}

This is more helpful than "value", especially if you have multiple parameters:

public Actor(String theName, String theFilm)
{
    name = theName;
    film = theFilm;
}

(and yes, I used used to use "this." but found it got cumbersome and error-prone)

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