Hello and welcome back for another series of articles here. This time a real C# relevant topic, not just .NET in general. So let's start ....
Have you ever wished to keep information only in a method and can re-access to it when the method is called again?
I barely remembered something, that Visual Basic provided back in the days: The static variable declaration in a method:
Sub Method1() Static myInt As Integer myInt = myInt + 1 MsgBox("myInt is now" & myInt) End Sub
The myInt is incremented every time Method1 is called. This feature is pretty cool if you want to encapsulate some information which needs only be accessed by exactly one method. However this feature also exists for VB.NET but not for C#.
The main reason people often tell you is:
- C# is an object oriented language and therefore methods should not have state, only objects should have.
On the other hand, some people say, the feature would be hard to implement. Well, I doubt that a little bit, but I'm not expert in here ...
And most people stated, that you can use a variable on class level (member or static), and then just use it in one method. Of course I could do this, but in a world where new code becomes legacy codes in just some weeks, I don't like to ponder whether I should use the variable also in other methods or not, when modifying code afterwards - especially if the original code was not by me.
So I combed the internet and found some interesting articles on StackOverflow. But the materials there did not satisfy me, so I took it and tried to refine and tickle a nice workaround to achieve a home-brew feature - that was the plan. Thanks to all StackOberflow contributers on the mentioned article!
As a first attempt I tried to solve the static persistent variables for method scopes only. Later on, we will try to solve the persistent variables in methods scopes only for non-static values as well.
Read the next article when we have to think about the following Questions:
- What serves as identifiers to keep theses persistent values, while the method is not running?
- How can we access these values through normal variables, so it feels comfy?
No comments:
Post a Comment