Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same Variable, different result

Tags:

c#

I just started out learning c# and I came across something confusing, I hope someone can explain it to me :)

namespace WindowsFormsApplication4
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        int Md = 0;

        private void cmdAnzeigen1_Click(object sender, EventArgs e)
        {
            int x = 0;
            Md = Md + 1;
            x = x + 1;
            lblErgebnis.Text = "x: " + x + "\n" + "Gx:" + Md;       
        }
    }
}

How come Md always increases by 1, but x doesn't (stays at 1)? I don't understand, they are both the same variables.

like image 746
vplusm Avatar asked Jun 30 '26 12:06

vplusm


1 Answers

Md is an instance variable, declared outside any method. It's part of the state of the object, so it "lives" (and maintains its value) for as long as the object is "alive". Different instances of Form1 would have independent Md variables.

x is a local variable - there's a new variable every time you call the method, and it always starts with a value of 0.

If that isn't enough explanation, please consult a good introductory C# book or tutorial - explaining everything about variables would be a bit much for Stack Overflow, which is more for handling specific problems than learning the fundamentals of a programming language.

like image 60
Jon Skeet Avatar answered Jul 02 '26 01:07

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!