Difference between struct and classes – Good to know series

Structs are value types so their memory allocation is stored in Stack in the memory on your computer and the class is stored on heap which is a different location the logical memory. The reason behind that is structs are value types and classes are reference type. So if you pass a struct to a method and change the value of that the object you will see that the value is changed within that scope of the method. On the other hand if you do the same with a class and pass it to a method. In that method if you update the value of the object. You will see that the value of the actual object is also changed. see the example below

class Program
	{
		static void Main(string[] args)
		{
			var st = new NameStruct();
			st.FirstName = "Asad";
			st.LastName = "Mirza";
 
			Console.WriteLine("values before passing " + st.FirstName + "  " + st.LastName  );
			updateStructValues(st);
			Console.WriteLine("values after passing " + st.FirstName + "  " + st.LastName);
 
			Console.WriteLine("Class Object ");
 
			var cl = new NameClass();
			cl.FirstName = "Asad";
			cl.LastName = "Mirza";
 
			Console.WriteLine("values before passing " + cl.FirstName + "  " + cl.LastName);
			updateClassValues(cl);
			Console.WriteLine("values after passing " + cl.FirstName + "  " + cl.LastName);
 
			Console.ReadLine();
		}
 
		private static void updateStructValues(NameStruct st)
		{
			st.FirstName = "Ali";
			Console.WriteLine("values updated " + st.FirstName + "  " + st.LastName);
		}
 
		private static void updateClassValues(NameClass cl)
		{
			cl.FirstName = "Ali";
			Console.WriteLine("values updated " + cl.FirstName + "  " + cl.LastName);
		}
	}
 
	public struct NameStruct
	{
		public string FirstName { get; set; }
		public string LastName { get; set; }
	}
 
	public class NameClass
	{
		public string FirstName { get; set; }
		public string LastName { get; set; }
	}

 

The output from that code is

values before passing Asad Mirza
values updated Ali Mirza
values after passing Asad Mirza
Class Object
values before passing Asad Mirza
values updated Ali Mirza
values after passing Ali Mirza

So you see for the class object the actual value is updated