Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Interface without static typing

Tags:

c#

Is there way to do something along these lines?

interface Iface
{
  [anytype] Prop1 { get; }
  [anytype] Prop2 { get; }
}

class Class1 : Iface
{
  public string Prop1 { get; }
  public int Prop2 { get; }
}

class Class2 : Iface
{
  public int Prop1 { get; }
  public bool? Prop2 { get; }
}

I don't care about the type of the properties, I just need the properties to be available. This doesn't have to be implemented with an interface, just using that as an example.

like image 828
zrg Avatar asked Aug 13 '10 14:08

zrg


4 Answers

Make the interface generic:

interface Iface<T1,T2>
{
   T1 Prop1  { get; }
   T2 Prop2  { get; }
}

Alternatively, make the properties of type object:

interface Iface
{
   object Prop1  { get; }
   object Prop2  { get; }
}

If you're using .NET 4.0 you could even make the properties of type dynamic:

interface Iface    {
   dynamic Prop1  { get; }
   dynamic Prop2  { get; }
}
like image 84
LBushkin Avatar answered Oct 19 '22 05:10

LBushkin


use object, or a generic Iface<TValue1,TValue2>

like image 37
kbrimington Avatar answered Oct 19 '22 05:10

kbrimington


You would have to either use object or provide a generic interface.

The generic version would look like:

interface IFace<T1, T2>
{
   T1 Prop1 { get; }
   T2 Prop1 { get; }
}

This will let the implementing type give those properties whatever type it wants, but the downside is that whenever you accept the interface you need to specify those two types:

public void DoSomething(IFace<int, string> sadFace)
...

This is usually problematic, very limiting at least, it can be "solved" by giving the interface a base interface where both properties are available with object return types.

I think the best solution, short of rethinking your approach is to define an interface IFace:

interface IFace
{
   object Prop1 { get; }
   object Prop1 { get; }
}

Then in your class implement the interface explicitly like so:

class MyClass: IFace
{
   public string Prop1 { get; }
   public int Prop2 { get; }

   object IFace.Prop1 { get; }
   object IFace.Prop1 { get; }
}

This will allow users who know the object is of type MyClass to refer to Prop1 and Prop2 by their actual types and anything using IFace can use the properties with a return type of object.

Myself I've used something looking like the last bit of code, and even the "generic interface with base interface" version above, but that was a very specialized scenario and I don't know if I could've solved it any other way.

like image 3
Skurmedel Avatar answered Oct 19 '22 05:10

Skurmedel


That rather defeats the objective of an Interface and would violate the strict typing of C#, not even a dynamic would help you out there I fear. The answer is no I believe.

like image 1
Lazarus Avatar answered Oct 19 '22 06:10

Lazarus