Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Method scope variable that retains value #1890

Closed
jheysonlima opened this issue Sep 26, 2018 · 3 comments
Closed

Method scope variable that retains value #1890

jheysonlima opened this issue Sep 26, 2018 · 3 comments

Comments

@jheysonlima
Copy link

This would be nice to keep control variables organized and only visible to the method that uses it.

(Silly)Example: I want to keep a counter of how many times a method was called, something like this

private int _callCount = 0;
public void CallMe() {
_callCount++;
if(_callCount == 10) System.Console.WriteLine("called 10 times");
}

in this case "_callCount" could be modified by any other method in the same class and it's also a bit messy to find a good place to declare it, since it's declared in a higher scope, but it is (or should be) only used by the "CallMe" method.

Suggestion:
the use of a keyword (I think "in" is a good fit) to declare the variable inside the method and to make it visible only to the method that created it "but also retaining the value between calls", something like this:

public void CallMe() {
in int _callCount = 0;
_callCount++;
if(_callCount == 10) System.Console.WriteLine("called 10 times");
}

in int _callCount = 0; means that if the variable does not exist it should be created but if it already exists this line would be ignored and it's value wouldn't change, keeping the previous value intact, I believe it could also be used with static keyword to create static variables inside static methods if the variable was not created yet, like:
static in int _callCount = 0;

I believe it's a good way of keeping the code clean and more secure since other methods woudn't be able to change each others control variables, it also looks like a good place to declare control variables (inside the method that uses it)

Anyway, thanks for reading it!

@HaloFour
Copy link
Contributor

#832

@gafter
Copy link
Member

gafter commented Sep 26, 2018

Closing as duplicate.

@gafter gafter closed this as completed Sep 26, 2018
@mekb-turtle
Copy link

Use block code by

  • indenting each line,
  • or putting ``` before and after the code,

for neater code in markdown.
Also is this issue #2413 a duplicate of this or another?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants