Ryan Jensen
Ryan Jensen

Reputation: 101

Issues with List.Add method when using a variable in C#

I currently am unable to use a variable that is a string to Add as an item to a list. It simply returns null when I pull the list later:

public class JobStatus
{

    public static string _JobURI;
    public static string currentStatus = "no job";

    public static void checkStatus()
    {

        ...
        //define job URI
        List<string> jobURIs = new List<string>();
        jobURIs.Add(_JobURI);

However, when I insert a string value like below instead of a variable, it adds it properly to the list:

//define job URI
List<string> jobURIs = new List<string>();
jobURIs.Add("new item name");

I'm not sure what I'm missing.

Upvotes: 0

Views: 178

Answers (2)

Ryan Jensen
Ryan Jensen

Reputation: 101

I figured it out, beginning programmer mistake. I used the Get Set method in the same class and declared the variable as well you all suggested above:

public static string currentStatus = "no job";

        private static string joburi = "";
        public static string JobURI
        {
            get { return joburi; }
            set { joburi = value; }
        }

Thank you for your help.

Upvotes: 0

Tim
Tim

Reputation: 28520

Based on your posted code, the reason you are getting null for _JobsURI is that you declare it here:

public static string _JobURI;

But you never assign it a value. Per the documentation: "A string that has been declared but has not been assigned a value is null."

Try assigning a value to _JobURI and then adding it to the List<string>:

public static string _JobURI = "Some string here.";

Upvotes: 2

Related Questions