If I do something like:

Label _label = label1;
_label.Text = "123";

Would label1 read "123"? Does this work for int and string?
If not, how would I achieve this?

Recommended Answers

All 5 Replies

it will work for a string, but not for an int.
The easiest is to convert the int to string, like:

int i = 25.
_label.Text = i.ToString();

hope it helps

Just so i'm clear, did you mean:

int x;
int y = x;
y = 1; //x now also equals 1

If you mean the code above then no, it wouldnt work. What you are looking at here is the difference between a value and a reference type.
The clue is in the name here, Value types are passed by value whilst Reference types are passed by reference.
Your label is a reference type so when you call Label _label = label1; , you are storing a reference to label1 in the variable called _label. When you make changes to _label, you are applying the changes to the label that the variable references.
With the int, when you call int y = x; , the value of x is copied into the variable called y. So when you make changes to y, x remains unchanged.

If you are passing the value type to a method you can pass it by reference to reflect the changes on the original using the 'ref' keyword:

class Program
    {
        static void Main(string[] args)
        {
            int x = 0;
            Console.WriteLine("Initial x = {0}", x); //x=0
            ValueMethod(x);
            Console.WriteLine("x After value method = {0}", x); //x=0
            ReferenceMethod(ref x);
            Console.WriteLine("x After Reference Method = {0}", x); //x=1

            Console.ReadKey();
        }

        private static void ValueMethod(int y)
        {
            y = y + 1;
        }

        private static void ReferenceMethod(ref int y)
        {
            y = y + 1;
        }

    }

I have two List<Label> arrays.
Would it be better to do:

Label label = new Label();
if (etc)
  label = List1[0];
else
  label = List2[0];
label.Text = "123";

or:

if (etc)
  List1[0].Text = "123";
else
  List2[0].Text = "123";

If you are only going to change that one property of the label inside the for loop then i would use the second option. If you need to repeatedly access the label then the second one (with a meaningful name for label variable) would make your code mroe readbale and reduce clutter.

If you are only going to change that one property of the label inside the for loop then i would use the second option. If you need to repeatedly access the label then the second one (with a meaningful name for label variable) would make your code mroe readbale and reduce clutter.

Okay, thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.