views:

60

answers:

2

Ok guys

I basically have a class which takes in 3 strings through the parameter of one of its method signatures.

I've then tried to map these 3 strings to global variables as a way to store them.

However, when I try to call these global variables from another class after instantiating this class they display as null values.

this is the class which gets the 3 strings through the method setDate, and the mapping..

 public class DateLogic
{

    public string year1;
    public string month1;
    public string day1;

    public DateLogic()
    {


    }

    public void setDate(string year, string month, string day) {

        year1 = year;
        month1 = month;
        day1 = day;


    // getDate();

    }

    public string getDate() {
     return year1 + " " + month1 + " " + day1;
    }

}

After this I try call this class from here

 public static string TimeLine2(this HtmlHelper helper, string myString2)
    {


        DateLogic g = new DateLogic();

        string sday = g.day1;
        string smonth = g.month1;
        string syr = g.year1;
    }

I've been debugging and the values make it all the way to the global variables but when called from this class here it doesnt show them, just shows null.

Is this cause I'm creating a brand new instance, how do i resolve this?

+6  A: 

year1, month1 and day1 are not "global variables" - they are instance fields that are defined for that type. Each DateLogic instance has separate fields.

You could achieve what you want by using static fields, but that is asking for lots of trouble (especially if your code is threaded or running on a web-server, which is implied by HtmlHelper) - it would be much better to pass the configured DateLogic instance to the code that needs it.

Marc Gravell
A: 

You're missing a call to g.setDate in TimeLine2.

Also, FYI, they aren't "global" variables. A global variable would be accessible without the object reference and is not what you want here anyway. You are talking about class variables.

Zarigani