1

I have this piece of code :

var takbis = o.DeserializeXmlString<List<Takbis>>();
ViewBag.SessionId = id;
_takbis.GetTakbisValues(takbis, vm);

I want to apply try-catch like this :

try
{
var takbis = o.DeserializeXmlString<List<Takbis>>();
}
catch
{
var takbis = o.DeserializeXmlString<BankReport>();
}

    ViewBag.SessionId = id;

    _takbis.GetTakbisValues(takbis, vm);

But I can't use it like this it says takbis does not exist in current context. I don't know the type of takbis, so I can't declare it before try catch. How can I solve this situation? Thanks.

sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
jason
  • 6,962
  • 36
  • 117
  • 198
  • The error message is self explanatory. You have defined it inside try which will make is in-accessible outside. – A3006 Sep 22 '16 at 05:58
  • Similar to this one, but this is `for loop`: http://stackoverflow.com/a/1196965/1050927 – Prisoner Sep 22 '16 at 05:59
  • What does `GetTakbisValues` accept as parameters ? It is `object` ? If so, define `object takbis;` before the `try` can set it inside the `try` and `catch`. – Zein Makki Sep 22 '16 at 06:03

4 Answers4

3

Try this:

object takbis;
try
{
    takbis = o.DeserializeXmlString<List<Takbis>>();
}
catch
{
    takbis = o.DeserializeXmlString<BankReport>();
}

    ViewBag.SessionId = id;

    _takbis.GetTakbisValues(takbis, vm);
Aleksandar Matic
  • 789
  • 1
  • 9
  • 21
3

I suggest you to use dynamic instead for var and use the code like this. If you use var then the type of variable declared is decided by the compiler at compile time. but in the case of dynamic the type of variable declared is decided by the compiler at runtime time.

try this:

dynamic takbis;
try
{
   takbis = o.DeserializeXmlString<List<Takbis>>();
}
catch
{
   takbis = o.DeserializeXmlString<BankReport>();
}

Read more about the comparison

sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
2

It is impossible. The variable must be declared outside of the try clause in order for it to be used later.

Inbar Barkai
  • 282
  • 1
  • 3
  • 12
2

For your information, var are processed at compile time not at run time. Also var is not actually a type, its actual type is replaced by compiler. You can either check in your compiled code about the type of your `var'

Rohit Rohela
  • 422
  • 6
  • 21