Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Interfaces: Is it possible to refer to the type that implements the interface within the interface itself?

Tags:

c#

interface

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?

like image 939
Knarf Navillus Avatar asked Jul 25 '10 17:07

Knarf Navillus


2 Answers

Why don't you create an abstract class? This way you can build some "default" functionality into your class.

like image 153
TheCloudlessSky Avatar answered Sep 30 '22 01:09

TheCloudlessSky


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).

like image 31
cwap Avatar answered Sep 30 '22 00:09

cwap