I am new to C# programming and I am currently using many static variables in my code. Below is one example:
class Program
{
public int I//Can be used to access the variable i anywhere from the code as it is public
{
get { return i; }
set { i = value; }
}
static int i = 0; // A private static integer
static void Main(string[] args)
{
i = 1;// The main function is changing this integer
}
void reset() {
i = 0;// another function is changing the value of integer i
}
}
class otherclass
{
void otherreset()
{
Program program = new Program();
program.I = 1;// another function in another class is changing the value of integer i(indirectly)
}
}
I did find this thread about using static variables in C# but I'd like to know, if this is a standard practice from a security perspective. I am concerned that the variable resides in the same location in memory throughout the execution of the program.
Are there any other better ways in general to share a variable between various functions.
static int i = 0; // A private static integer
Here you declared a static member. So far so good.
static void Main(string[] args)
{
int i = 1;// The main function is changing this integer
}
No, it doesn't. int i
means you declared a new local variable named i
.
void reset() {
int i = 0;// another function is changing the value of integer i
}
No, it doesn't. int i
means you declared a new local variable named i
.
I'd like to know if this is a standard practice from a security perspective.
No, it isn't, and no, it's not related to security. You should avoid using static members as much as possible. I think that the actual reasons why are, currently, way too far from your current level of knowledge and understanding. Just take it as a best practice.
I am concerned that the variable resides in the same location in memory throughout the execution of the program.
Well, a variable that would 'travel' between memory locations wouldn't be a good idea :-) Variables are, very simplistically put, named locations in memory.
are there any other better ways in general to share a variable between various functions.
Yes, start by learning about function parameters, member fields, and properties. Use whatever beginner C# book you have available, or search online.