CSharp examples for Custom Type:struct
Compare struct and class as value type and Reference type
using System;/*w w w . j a v a 2 s . c om*/ //Create a value type public struct Point { public int x; public int y; } //Create a Reference type public class MyObject { public int i; } public class Pass { public static void Main( ) { int i = 100; Console.WriteLine("Value of i before PassByValue Method is {0}", i ); PassByValue( i ); Console.WriteLine("Value of i after PassByValue Method is {0}", i ); Console.WriteLine("Value of i before PassByRef Method is {0}", i ); PassByRef( ref i ); Console.WriteLine("Value of i before PassByRef Method is {0}", i ); //Create an the Point type Point p; p.x = 10; p.y = 15; Console.WriteLine("Value of p before PassByValue is x={0}, y={1}", p.x,p.y); PassByValue( p ); Console.WriteLine("Value of p after PassByValue is x={0}, y={1}", p.x,p.y); Console.WriteLine("Value of p before PassByRef is x={0}, y={1}", p.x,p.y); PassByRef( ref p ); Console.WriteLine("Value of p after PassByRef is x={0}, y={1}", p.x,p.y); //Create an object instance MyObject o = new MyObject( ); o.i = 10; Console.WriteLine("Value of o.i before PassReferenceType is {0}", o.i ); PassReferenceType( o ); Console.WriteLine("Value of o.i after PassReferenceType is {0}", o.i ); } public static void PassByValue( Point p ) { Console.WriteLine( "Value of Point.x = {0} : Point.y = {1}", p.x, p.y ); p.x++; p.y++; Console.WriteLine( "New Value of Point.x = {0} : Point.y = {1}", p.x, p.y ); } public static void PassByValue( int i ) { Console.WriteLine("Value of i = {0}", i ); i++; Console.WriteLine("New Value of i = {0}", i ); } public static void PassByRef( ref Point p ) { Console.WriteLine("Value of Point.x = {0} : Point.y = {1}", p.x, p.y ); p.x++; p.y++; Console.WriteLine("New Value of Point.x = {0} : Point.y = {1}", p.x, p.y ); } public static void PassByRef( ref int i ) { Console.WriteLine("Value of i = {0}", i ); i++; Console.WriteLine("New Value of i = {0}", i ); } public static void PassReferenceType( MyObject o ) { Console.WriteLine("Value of MyObject.i = {0}", o.i); o.i++; Console.WriteLine("New Value of MyObject.i = {0}", o.i); } }