简体   繁体   中英

It is allowed to put private variables inside public methods in C#?

I have a little code

public void StartConnection(){
  _connection = new DatabaseConnection();
}

public Results ExecuteQuery( string format ){
  _queryExecuter.SetText = string.Format(_queryString, format);

  return _queryExecuter.Execute();
}

What I did, it allowed to use private members inside public methods ?

I mention that public methods will be used in another classes (from different project but in same solution).

Or I have to create private methods and use inside the private variables ?

I need just advices.

Thank you

Yes its a very fundamental programming philosophy called encapsulation . Its perfectly valid and encouraged to do so. In your case, only you know how to use your connection object and "restrict" how to use it via your public method, thus keeping your application in your defined bounds.

What I did, it allowed to use private members inside public methods ?

Yes, you can absolutely use private members within public ones. They'd be pretty useless otherwise! (If you could only use private members within other private members, how could you ever use any of them?)

A lot of the point of encapsulation is to hide the implementation details (the private members) from the public API.

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