Is it possible to use C# generics replace these 4 routines with one?
int memcmp (string a, string b){...}
int memcmp (string a, byte[] b){...}
int memcmp (byte[]a, string b){...}
int memcmp (byte[]a, byte[] b){...}
I've tried a number of variations, but cannot determine exactly what to use...
For example...
int memcmp<A, B>( A a, B b)
{
if ( a.Length < b.Length ) return 1;
for ( int i = 0 ; i < a.Length ; i++ )
{
if ( a[i] != b[i] ) return ( a[i] < b[i] ) ? -1 : 1;
}
}
gives the following errors:
Where is a good reference that discusses this?
**NOTE: ** I am not looking for a solution on how to compare strings and bytes, rather seeking an understanding of how generics work in C# using a "proof-of-concept" problem
Your ideal solution would have a signature of:
int memcmp<T>( T a, T b ) where T : IHasLengthAndIndexer
where IHasLengthAndIndexer
is defined as:
public interface IHasLengthAndIndexer
{
int Length { get; }
byte this[ int index ] { get; }
}
Then you could pass in any type assuming the type implements IHasLengthAndIndexer
However you cannot change the interfaces of byte[]
and string
so this solution would not replace your four methods.
You could, however, create your own class that has implicit operators from byte[]
and string
and create a method that compares instances of that class, but that isn't using generics.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With