Reputation: 7164
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.
Upvotes: 1
Views: 1674
Reputation: 422
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'
Upvotes: 2
Reputation: 29006
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
Upvotes: 3
Reputation: 799
Try this:
object takbis;
try
{
takbis = o.DeserializeXmlString<List<Takbis>>();
}
catch
{
takbis = o.DeserializeXmlString<BankReport>();
}
ViewBag.SessionId = id;
_takbis.GetTakbisValues(takbis, vm);
Upvotes: 3
Reputation: 302
It is impossible. The variable must be declared outside of the try clause in order for it to be used later.
Upvotes: 2