How to use struct by ref and out in C#

1 Answer

0 votes
using System;

namespace struct_by_ref_and_out
{
	struct Test
	{
		public int x;
	}
	class Class1
	{
		static void ChangeVal(Test t)
		{
			t.x = 400;
		}
		static void ChangeRef(ref Test t)
		{
			t.x = 100;
		}
		static void ChangeOut(out Test t)
		{
			t.x = 255;
		}
		static void Main(string[] args)
		{
            Test t_val = new Test();

            t_val.x = 7;
            ChangeVal(t_val);
            Console.WriteLine("by val t_val.x = {0}", t_val.x); // by val t_val.x = 7

			Test t_ref = new Test();

            t_ref.x = 7;
            ChangeRef(ref t_ref);
            Console.WriteLine("by ref t_ref.x = {0}", t_ref.x); // by ref t_ref.x = 100

			Test t_out = new Test();

			ChangeOut(out t_out);
			Console.WriteLine("by out t_out.x = {0}", t_out.x); // by out t_out.x = 255
		}
	}
}



answered Aug 5, 2014 by avibootz

Related questions

1 answer 340 views
1 answer 225 views
225 views asked Aug 12, 2021 by avibootz
2 answers 320 views
2 answers 367 views
1 answer 214 views
214 views asked Aug 12, 2021 by avibootz
2 answers 339 views
2 answers 295 views
...