I got a class in C# that has multiple overloads for different parameter types:
class Writer
{
public Writer Write(bool value)
{
// Do something with value
return this;
}
public Writer Write(double value)
{
// Do something with value
return this;
}
public Writer Write(int value)
{
// Do something with value
return this;
}
public Writer Write<T>(T value) where T : class, IInterface, new()
{
// Do something with value
return this;
}
}
class Reader
{
public Reader Read(out bool value)
{
// Retrieve value
return this;
}
public Reader Read(out double value)
{
// Retrieve value
return this;
}
public Reader Read(out int value)
{
// Retrieve value
return this;
}
public Reader Read<T>(out T value) where T : class, IInterface, new()
{
// value = new T() or null
return this;
}
}
Now I want to call Write
and Read
for multiple variables in a row, one of which is of an enum
type. However, that enum type causes difficulties in the method resolving. (Btw: I am used to VB.NET, where Enum
types are compatible to Integer
parameters.)
enum MyEnum : int
{
Foo = 0, Bar = 1
}
class CallingClass
{
public void Call()
{
bool b;
double d;
int i;
IInterface o;
MyEnum e = MyEnum.Foo;
var w = new Writer();
// Unintuitive for Write
w
.Write(b)
.Write(d)
.Write(i)
.Write(o)
.Write((int) e);
// w.Write(e); // resolves to Writer.Write<T>(T)
// => Compile error: "MyEnum has to be reference type to match T"
// Even worse for Read, you need a temp variable
// and can't use fluent code anymore:
var r = new Reader();
r
.Read(out b)
.Read(out d)
.Read(out i)
.Read(out o);
int tmp;
r.Read(out tmp);
e = (MyEnum) tmp;
}
}
Is there any way I can modify Write
/Read
, Writer
/Reader
or MyEnum
so that w.Write(e)
will automatically resolve to Writer.Write(int)
and more importantly r.Read(out e)
to Reader.Read(int)
?