1

Why would it return rainyday[1] = Sunday and not friday ?? and elsewhere returning all the values defined in main()

  Namespace ConsoleApp_toTestYourself
    {
        public struct forecast
        {
            public int temp { get; set; }
            public int press { get; set; }
        }


        class structStaticTest
        {
            public static void cts(string weather) { weather = "sunny"; }
            public static void cta(string[] rainyDays) { rainyDays[1] = "Sunday"; }
            public static void ctsr(forecast f) { f.temp = 35; }

            static void Main(string[] args)
            {
                string weather = "rainy";
                cts(weather);   //calling static method
                Console.WriteLine("the weather is " + weather);

                string[] rainyDays=new[]{"monday","friday"};
                    cta(rainyDays);  calling static method
                Console.WriteLine("the rain days were on "+rainyDays[0]+"  and   "+ rainyDays[1]);

                forecast f = new forecast { press = 700, temp = 20 };
                ctsr(f);  //calling static method
                Console.WriteLine("the temperature is  " + f.temp + "degree celcius");
                Console.ReadLine();
            }
        }
    }

Its output is : Rainy Monday Sunday 20 degree celcius

Technovation
  • 397
  • 2
  • 12
svik
  • 212
  • 2
  • 12

2 Answers2

4

Because cta method sets rainyDays[1] to Sunday:

public static void cta(string[] rainyDays) { rainyDays[1] = "Sunday"; }

And it's called right before writing to console:

cta(rainyDays);  //calling static method
Console.WriteLine("the rain days were on "+rainyDays[0]+"  and   "+ rainyDays[1]);

EDIT: On differences between your static methods. Other methods don't change passed objects.

First, cts doesn't change string object:

weather = "sunny";

doesn't change original object. It creates new string object "sunny" and assigns it to a variable (method argument).

More on this topic:

Second, ctsr accepts struct forecast as an argument. Structs are passed by value, method receives and operates on a copy of original struct. So, your changes don't have any effect on weather in main method.

More on this topic:

Community
  • 1
  • 1
default locale
  • 13,035
  • 13
  • 56
  • 62
1

it's because of difference between reference types and value types in c#, structs are value types, when you receive a struct as an argument a different copy of that will create, so if you change one of them, the other does not change. the variable (f) holds the struct's actual data which is on stack, against reference types, which the variable holds only a reference to the memory location which is on heap (actual data) and pointer itself is on stack. in case of rainyday[1] = Sunday you changed the original data, because there is no copy and you are working on original data.

Technovation
  • 397
  • 2
  • 12