1

Given this F#:

namespace DU_Sample  

type StateA = { Counter: int }  
type StateB = { Counter: int; Pass: bool }  

type DU =  
| A of StateA  
| B of StateB  

And this C#:

[TestMethod]  
public void TestMethod1()  
{  
  var stateB = GetStateB();  
  Assert.IsTrue( stateB.IsB );  
  //Assert.IsTrue( ((DU_Sample.StateB)stateB).Pass );  // nope  
  //var nutherB = DU_Sample.DU.NewB( stateB );  // nope  
  Assert.IsTrue( ( (dynamic)stateB ).Item.Pass );  // pass  
}  

private static DU_Sample.DU GetStateB()  
{  
  var stateB = new DU_Sample.StateB( 0, true );  
  return DU_Sample.DU.NewB( stateB );  
}

How can I cast the Discriminated Union type to one of it's parts in order to access that part's properties?

ildjarn
  • 62,044
  • 9
  • 127
  • 211
dudeNumber4
  • 4,217
  • 7
  • 40
  • 57

1 Answers1

1

In both cases you have to (down) cast and then use the property Item:

Assert.IsTrue((stateB as DU_Sample.DU.B)?.Item.Pass ?? false); 
var nutherB = DU_Sample.DU.NewB(((DU_Sample.DU.B)stateB).Item)
Gus
  • 25,839
  • 2
  • 51
  • 76