What I basically wish to do is design a generic interface that, when implemented, results in a class that can behave exactly like T, except that it has some additional functionality. Here is an example of what I'm talking about:
public interface ICoolInterface<T>
{
T Value { get; set; }
T DoSomethingCool();
}
public class CoolInt : ICoolInterface<int>
{
private int _value;
public CoolInt(int value)
{
_value = value;
}
public int Value
{
get { return _value; }
set { _value = value; }
}
public int DoSomethingCool()
{
return _value * _value;
// Ok, so that wasn't THAT cool
}
}
And this is all well and good, but in order to use CoolInt, I need to do something like this:
CoolInt myCoolInt = new CoolInt(5);
int myInt = myCoolInt.Value;
I'd much rather, in terms of assignment at least, that CoolInt works just like int. In other words:
CoolInt myCoolInt = 5;
int myInt = myCoolInt;
To achieve this, I added these two conversion operators to my CoolInt class:
public static implicit operator CoolInt(int val)
{
return new CoolInt(val);
}
public static implicit operator int(CoolInt obj)
{
return obj.Value;
}
Works awesomely. Now, I would prefer it if I could add these two overloads to the interface, so that implementers of the interface are forced to implement these operators. The problem is, the prototypes of these operators refer directly to CoolInt.
C# has a lot of "placeholder" names for things that are implicitly defined or have yet to be defined. The T that is conventionally used in generic programming is one example. I suppose the value keyword, used in Properties, is another. The "this" reference could be considered another. I am hoping that there's another symbol I can use in my interface to denote "the type of the class that is implementing this interface", e.g. "implementer".
public static implicit operator implementer(int val)
{
return new IntVal(val);
}
public static implicit operator int(implementer obj)
{
return obj.Value;
}
Is this possible?
Why don't you create an abstract class? This way you can build some "default" functionality into your class.
Sadly no :(
C# doesn't do well when it comes to operator overloading (This is one example, another is generic constraints on certain operator types).
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