Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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#?

like image 362
prosseek Avatar asked Dec 15 '10 20:12

prosseek


3 Answers

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.

like image 157
cdhowie Avatar answered Sep 25 '22 01:09

cdhowie


You can do this. Just use:

public void SetUid(int uid) { this.uid = uid; }
like image 26
Matt Kellogg Avatar answered Sep 23 '22 01:09

Matt Kellogg


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

 public void SetUid(int uid)
 {
    this.uid = uid;
 }
like image 36
Kim Gräsman Avatar answered Sep 22 '22 01:09

Kim Gräsman