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.
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; }
}
use object
, or a generic Iface<TValue1,TValue2>
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.
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.
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