Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a generic unbox function like in f#?

Tags:

c#

f#

unboxing

I m trying to use object handlers and I have this working fine to put stuff in memory. But when I look up the object again I return:

object(object[,]) 

or

object(double[,]) 

how do I unbox this in c#?

object(double[,]) boxedobj = ....
double[,] unboxedobj = unbox(boxedobj);

Ideally I would like to do this in a generic way so that it doesnt matter whether the tybe is double[] or double[,] or object[,], etc

like image 736
nik Avatar asked Dec 28 '25 16:12

nik


1 Answers

The F# unbox function is pretty much just doing cast to any other type that you specify. In C#, this could be written like this:

static R Unbox<R>(object anything) {
  return (R)anything;
}

So in your case with double[,] you'd need something like:

var array = (double[,])boxed;

In most cases unbox<'R> anything would just translate to casting using (R)anything. The only case where this does not work is when you are in another generic method and you are casting between two generic types. In that case, you need to go to object first (to make sure that the value is boxed):

static R Unbox<R, T>(T anything) {
    return (R)(object)anything;
}
like image 123
Tomas Petricek Avatar answered Dec 31 '25 04:12

Tomas Petricek