Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple type test in F#

Tags:

f#

c#-to-f#

I've been googling for a while now... Ok, I'm sorry, this one is pathetically easy but is there an operator in F# to compare class types, like the 'is' keyword in C#? I don't want to use a full blown match statement or start casting things. Cheers

like image 970
Ed Ayers Avatar asked Jun 10 '11 13:06

Ed Ayers


2 Answers

You can use the :? construct both as a pattern (inside match) or as an operator:

let foo = bar :? System.Random

This behaves slightly differently than in C#, because the compiler still tries to do some checks at compile-time. For example, it is an error to use this if the result would be surely false:

let bar = 42
let foo = bar :? System.Random // Error

I don't think this could lead to confusion, but you can always add box to convert the argument to obj, which can be tested against any type:

let foo = box bar :? System.Random
like image 140
Tomas Petricek Avatar answered Oct 18 '22 21:10

Tomas Petricek


If you want a general C#-to-F# quick-reference, see

http://lorgonblog.wordpress.com/2008/11/28/what-does-this-c-code-look-like-in-f-part-one-expressions-and-statements/

which answers this question and many others.

like image 34
Brian Avatar answered Oct 18 '22 21:10

Brian