Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use C# generics in place of string and byte[]

Tags:

c#

generics

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:

  • 'A' does not contain a definition for 'Length'
  • Cannot apply indexing with [] to an expression of type 'A'

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

like image 930
Noah Avatar asked Dec 08 '22 06:12

Noah


1 Answers

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.

like image 167
Tinister Avatar answered Dec 30 '22 14:12

Tinister