Click here to Skip to main content
15,884,099 members
Please Sign up or sign in to vote.
5.00/5 (2 votes)
See more:
Say I have the following :

C#
public class SomeClass<T> : where T : ICompareable<T> , IGetBytes<T>
{...


Now when I use the following :
C#
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
Updated 9-Nov-11 20:52pm
v2

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:


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

    // ...
}

and use your class with the wrapper:


C#
public class SomeClass<T>
{
    void MyMethod(T arg)
    {
        MyWrapperClass<T> wrappedArg = new MyWrapperClass<T>(arg);

        // ...
    }
}
 
Share this answer
 
v4
Comments
Mehdi Gholam 10-Nov-11 2:59am    
How about extension methods for the int?
Mehdi Gholam 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.
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.
 
Share this answer
 
v2
Comments
Mehdi Gholam 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.
Sander Rossel 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)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900