-3

I box value types:

Object boxed = new Object();
boxed = "bla bla bla"; // boxing string
boxed = 10; //boxing int

At some point I need to unbox but before value is unboxed I need to check the type before it was boxed?

How can I check what is the type that boxed?

Michael
  • 13,950
  • 57
  • 145
  • 288
  • `GetType()` and `typeof`? - https://msdn.microsoft.com/en-us/library/system.object.gettype(v=vs.110).aspx – mihail Oct 31 '17 at 14:01
  • `if(boxed is FooType) ((FooType)boxed).SomeMethod()` – FCin Oct 31 '17 at 14:02
  • `.GetType()` works whether something is boxed or not. But you're using the wrong term to begin with -- you don't care if it's *boxed*, you want to know the type of an object that you've stored as a generic `Object`. Notably, you don't box strings, since they're reference types. – Jeroen Mostert Oct 31 '17 at 14:02
  • 1
    There are too many obvious answers to this question. What we can't tell is *why* you need to know, the snippet is particularly unhelpful. So you can't get the right answer. – Hans Passant Oct 31 '17 at 14:02
  • using `is` operator is the simplest way – Andrew Oct 31 '17 at 14:03
  • @HansPassant is correct. The correct answer depends on what you are doing. What is the context? – Guilherme Oct 31 '17 at 14:05
  • Strings cannot be boxed. They're reference types already. – Servy Oct 31 '17 at 14:05
  • "boxed = "bla bla bla"; // boxing string" there´s no boxing on string or any other reference-type. Boxing only occurs on value-types. – MakePeaceGreatAgain Oct 31 '17 at 14:07

1 Answers1

2

You can simply call GetType() or is:

if (boxed is int i)
{
    // use i
}

Or pre-C# 7:

if (boxed is int)
{
    int i = (int)boxed;
    // use i
}

String is a reference type already, so no boxing. int can be boxed, but still the underlying type returned is the unboxed type.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
  • The code example used in your answer is C#7, while it may be correct, there was no such version specified and it is not the mainstream version of the C# language, this answer may be confusing for some newbies. I would recommend adding such information. – mrogal.ski Oct 31 '17 at 14:06
  • Oh, yes. The user knows what boxing is, so not a newbie exactly. Will update. – Patrick Hofman Oct 31 '17 at 14:07