Snippets

Alex Darby Compare Struct Instances (note: if you need to do this you should really be using a class)

Created by Alex Darby last modified
using System;

namespace structRefChecker
{
	public struct TestStruct
	{
		static uint s_structIdGenerator = 0;

		private readonly	uint	m_structId;
		public				int		m_someValue;

		public TestStruct( int value )
		{
			m_someValue	= value;
			m_structId	= s_structIdGenerator++;
		}

		public static bool StructIdsMatch( TestStruct one,  TestStruct two )
		{
			return ( one.m_structId == two.m_structId );
		}

		// need to allow unsafe code for this to compile. In Visual studio this is: Project -> <projectname> properties -> Build -> [x] allow unsafe code
		public unsafe static bool AreSameInstance( ref TestStruct one, ref TestStruct two )
		{	
			fixed( TestStruct* pone = &one, ptwo = &two )
			{
				return pone == ptwo;
			}
		}
	}

	

	class Program
	{
		static void ProcessTestStructs( ref TestStruct one, ref TestStruct two )
		{
			Console.WriteLine( string.Format( "one and two have {0} ids", TestStruct.StructIdsMatch( one, two )?"the same":"different" ) );
			Console.WriteLine( string.Format( "one and two are {0}", TestStruct.AreSameInstance( ref one, ref two )?"the same":"different" ) );
		}			

		static void Main( string[] args )
		{
			var testOne = new TestStruct( 1 );
			var testTwo = new TestStruct( 2 );

			ProcessTestStructs( ref testOne, ref testTwo ); 
			ProcessTestStructs( ref testOne, ref testOne ); 
			ProcessTestStructs( ref testTwo, ref testTwo ); 

			// shortcoming of the id method - can'tr prevent or overload assignment of struct in C#
			testOne = testTwo;

			ProcessTestStructs( ref testOne, ref testTwo ); 


			Console.ReadKey();
		}
	}
}

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.