Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#
Say I have the following :
 
public class SomeClass<T> : where T : ICompareable<T> , IGetBytes<T>
{...
 
Now when I use the following :
 var s = new SomeClass<int>();
 
I get an error that :
The type 'int' cannot be used as type parameter 'T' in the generic type or method 'SomeClass<T>'. There is no boxing conversion from 'int' to 'IGetBytes<int>'.
 
How can I implement the IGetBytes for an int etc.
Posted 9-Nov-11 21:28pm
Mehdi Gholam266.8K
Edited 9-Nov-11 21:52pm
v2
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

You cannot implement interfaces in int because the code of System.Int32 isn't yours. But you can create a wrapper class that implements the interfaces as the following:

public class MyWrapperClass<T> : ICompareable<T>, IGetBytes<T>
{
    public MyWrapperClass(T arg)
    {
        // ...
    }
 
    // ...
}

and use your class with the wrapper:

public class SomeClass<T>
{
    void MyMethod(T arg)
    {
        MyWrapperClass<T> wrappedArg = new MyWrapperClass<T>(arg);
 
        // ...
    }
}
  Permalink  
v4
Comments
Mehdi Gholam at 10-Nov-11 2:59am
   
How about extension methods for the int?
Mehdi Gholam at 10-Nov-11 4:00am
   
5'ed, I'm still looking for a simpler way but a wrapper works for now. Actually I already had to do this for byte[] -> bytearr class in my app.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

What you are saying is that the type of T should be an IComparable of itself (int is an IComparable<int>) and that type T should also be an IGetBytes of <T>.
Int32 on MSDN[^] shows that the int structure is no IGetBytes<int> so it can not be used as type T here.
Look at Shmuel Zangs answer for a workaround. Although I am not sure you should use MyWrapperClass<T> because the implementation of IComparable and IGetBytes probably won't be generic for all types... Rather just create a MyIntWrapper Class.
  Permalink  
v2
Comments
Mehdi Gholam at 10-Nov-11 3:02am
   
There should be a way with say extension methods etc. ?
 
Actually I have done a similar thing with byte[] which I have mapped to a bytearr class of my own, but it seems a bit too much and there should be an easier way than reimplementing base types.
Naerling at 10-Nov-11 3:46am
   
As far as I know Extension Methods only extend with Methods (kind of as the name implies). Extending the behaviour of a complete type is usually done through Inheritance or composition... It would be interesting if this was possible though.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Advertise | Privacy | Mobile
Web03 | 2.8.150327.1 | Last Updated 10 Nov 2011
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100