What is the scope of public variable in different methods of a same class in Console C#

87 Views Asked by At

I have a class named Data that is used to retrieve a user's data

    class Data
    {
        public string firstName;
        public string lastName;
        public void getdata()
        {
            firstName = "ABC";
            lastName = "XYZ";
        }
        public static XDocument GetDataToXml()
        {
            var objget = new Data();
            objget.getdata();
            XDocument doc = new XDocument(
               new XElement("firstName ", objget.firstName),
               new XElement("lastName", objget.firstName));
            return doc;
        }
        public void display()
        {
            string fdata = firstName;  //i get "firstName"  value as null why????
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            var obj = new Data();
            obj.getdata();
            obj.display();
            Console.ReadLine();
        }
    }

Why do I get null value when I call disp() ,Also I just want to access the values of firstName and lastName in the GetDataToXml() even there the getData() function gets called.What is the scope of this variable in spite me assigning it as public?

1

There are 1 best solutions below

2
On BEST ANSWER

To help you a little i have redesigned your example :

class Program
{
    static void Main(string[] args)
    {
        var obj = new Data();
        obj.setData("First", "Last");
        obj.GetDataToXml();
        Console.ReadLine();
    }
}

class Data
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public void setData(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }
    public XDocument GetDataToXml()
    {
        XDocument doc = new XDocument(
           new XElement("FirstName ", FirstName),
           new XElement("LastName", LastName));
        return doc;
    }
}

Put a Breakpoint inside the GetDataToXML method and check both FirstName and LastName values.