Reputation: 1828
The below code throws an exception when executing this line (i.e. something.Add(name)).
I want to catch the actual exception when executing this. I mean I don't want to use catch(Exception ex) instead of that I want to know what is the correct exception thrown here.
try
{
dynamic name= "test";
var something = new List<decimal>();
something.Add(name);
}
catch(Exception ex)
{
throw ex;
}
Thanks in advance.
Upvotes: 3
Views: 8216
Reputation:
Type dynamic behaves like type object in most circumstances, it bypasses static type checking. At compile time, an element of dynamic type is is assumed to support any operation.
[Source: MSDN-1, MSDN-2]
In your case:
You may try following code:
try
{
dynamic name= "test";
var something = new List<decimal>();
something.Add(name);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
Console.WriteLine(ex.Message);
}
Example of dynamic type:
using System;
class Program
{
static void Main(string[] args)
{
dynamic dynVar = 2;
Console.WriteLine(dynVar.GetType());
}
}
Would output as:
System.Int32
List<decimal> dl = new List<decimal>();
dl.Add("Hello");
Upvotes: 1
Reputation: 693
Not sure why you're trying to cast a string to a decimal, but ok... The answer is Microsoft.System.CSharp.RuntimeBinder.RuntimeBinderException.
Source: Actually running the code. :)
Upvotes: 21