I am trying to implement a system where I need to have a C# class with property which type can be one of
types.
In F# this features called “Discriminated Unions”, in TypeScript it is called “Union Types”.
Here is an example of how I could implement it in TypeScript:
class Something {
public myField?: boolean | Date;
}
let something = new Something();
something.myField = true;
something.myField = new Date();
As far as I know it’s not possible in C#. What are the workarounds?
How would you (as C# developer) implement this?
Options I considered
-
Using
object
type might work in my case but I would like to have more precise solution. -
I’ve also tried to use implicit conversion but it looks too hacky
class MyFieldType {
private bool _valueBool;
private DateTime _valueDateTime;
public MyFieldType(DateTime value) {
_valueDateTime = value;
}
public MyFieldType(bool value) {
_valueBool = value;
}
public bool GetBool() {
return _valueBool;
}
public DateTime GetDateTime() {
return _valueDateTime;
}
public static implicit operator MyFieldType(bool value) {
return new MyFieldType(value);
}
public static implicit operator MyFieldType(DateTime value) {
return new MyFieldType(value);
}
public static implicit operator DateTime(MyFieldType value) {
return value.GetDateTime();
}
public static implicit operator bool(MyFieldType value) {
return value.GetBool();
}
}
class MyClass {
public MyFieldType? MyField;
}
1