A
Arash_89
Guest
Hello,
Why can we modified elements of object (This behavior seems to fly in the face of what it means to pass a parameter by value) but we cannot reassign new instance for it?
Given that I were able to change the incoming Person, What was copied?
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApp1
{
class Person
{
public Person() { }
public string Name;
public int Age;
public Person(string name,int age)
{
Name = name;
Age = age;
}
public void Display()
{
Console.WriteLine($"Name: {Name} - Age: {Age}");
}
}
class Program
{
static void Main(string[] args)
{
Person p = new Person("Daniel",20);
Console.WriteLine("Before Send");
p.Display();
Change(p);
Console.WriteLine("After Send");
p.Display();
}
static void Change(Person p)
{
p.Age = 100; //modified
p = new Person("Nikki",50); // NOT possible to reassign
}
}
}
Continue reading...
Why can we modified elements of object (This behavior seems to fly in the face of what it means to pass a parameter by value) but we cannot reassign new instance for it?
Given that I were able to change the incoming Person, What was copied?
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApp1
{
class Person
{
public Person() { }
public string Name;
public int Age;
public Person(string name,int age)
{
Name = name;
Age = age;
}
public void Display()
{
Console.WriteLine($"Name: {Name} - Age: {Age}");
}
}
class Program
{
static void Main(string[] args)
{
Person p = new Person("Daniel",20);
Console.WriteLine("Before Send");
p.Display();
Change(p);
Console.WriteLine("After Send");
p.Display();
}
static void Change(Person p)
{
p.Age = 100; //modified
p = new Person("Nikki",50); // NOT possible to reassign
}
}
}
Continue reading...