Lepid lanky February 2016

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);
    }
}

Answers


Patrick Hofman February 2016

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;
}

Post Status

Asked in February 2016
Viewed 1,308 times
Voted 7
Answered 1 times

Search




Leave an answer