In the below code, I am hoping to end up with both classA and Main to both thing that Main's name is "GoodBye" However, in the end, classA still things Main's name is 'Hello' while Main know's it's name has been changed to 'GoodBye'. How to I allow classA to see that Main's name has been changed to GoodBye?
Is this not allowed in C# and is deemed as unsafe and therefore you have to wrap the code inside of 'unsafe' blocks?
After testing I understand that using the reference allows classA to modify Main's name but doens't allow classA to see when Main's name has been changed.
class Program
{
static void Main(string[] args)
{
string MyName = "Hello";
Console.WriteLine($"Main thinks Main's name is: {MyName}");
Console.WriteLine($"");
Console.WriteLine($"Creating ClassA");
ClassA classA = new ClassA(ref MyName);
Console.WriteLine($"Main thinks Main's name is: {MyName}");
classA.WriteOutMainName();
MyName = "GoodBye";
Console.WriteLine($"");
Console.WriteLine($"Main changed it's name to: {MyName}");
Console.WriteLine($"");
Console.WriteLine($"Main thinks Main's name is: {MyName}");
classA.WriteOutMainName();
}
}
public class ClassA
{
string MainName;
public ClassA(ref string mainName)
{
MainName = mainName;
mainName = "Dog";
}
public void WriteOutMainName()
{
Console.WriteLine($"ClassA thinks Main's name is: {MainName}");
}
}
The output for the above is the following:
Main thinks Main's name is: hello Creating ClassA Main thinks Main's name is: hello ClassA thinks Main's name is: hello Main changed it's name to: GoodBye Main thinks Main's name is: GoodBye ClassA thinks Main's name is: hello Press any key to continue . . .