jason jason - 2 months ago 13
C# Question

How to use try catch with var in C#

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.

Answer

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

Comments