-using System.Threading.Tasks;
namespace structRefChecker
static uint s_structIdGenerator = 0;
- private uint m_structId;
- public int m_someValue;
+ private readonly uint m_structId;
+ public int m_someValue;
public TestStruct( int value )
m_structId = s_structIdGenerator++;
- public static bool IsSameInstance( TestStruct one, TestStruct two )
+ 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 )
static void ProcessTestStructs( ref TestStruct one, ref TestStruct two )
- if( TestStruct.IsSameInstance( one, two ) )
- Console.WriteLine( "one and two are the same instance" );
- Console.WriteLine( "one and two are different instances" );
+ 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 )
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#
+ ProcessTestStructs( ref testOne, ref testTwo );