Yugesh Gyawali
Yugesh Gyawali

Reputation: 146

Local variable and Global variable with same name and how it works?

Can someone please tell me the program flow and out of the given snippet.I tried this on VS and got 0 0 as output,and i want to know how this works. Thanks.

static void Main(string[] args)
{
    Sample s1 = new Sample();
    s1.getdata(10, 5.4f);
    s1.displaydata();
}

class Sample
{
    int i;
    Single j;
    public void getdata(int i,Single j)
    {
        i = i;
        j = j;
    }
    public void displaydata()
    {
        Console.WriteLine(i + " " + j);
    }
}

Upvotes: 4

Views: 2381

Answers (1)

Patrick Hofman
Patrick Hofman

Reputation: 157058

Since the local variables are preferred over the class variables, the class variables are never set. Inside the getdata method you are setting the local (method scoped) variables to their own value. Hence, in the displaydata method, you are printing the default values of the integers (0).

To fix this, you can either change the names of the variables, by prefixing them for example, or use this to set the scope.

public void getdata(int i,Single j)
{
    this.i = i;
    this.j = j;
}

Upvotes: 6

Related Questions