user972255
user972255

Reputation: 1828

C# Dynamic Keyword exception handling

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

Answers (2)

user841123
user841123

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:

  • This means, when you defined a variable of type dynamic it will be treated like object type, so you may store any value in it, and you may add it to List of decimal, compiler would not throw any error.
  • But at run-time the dynamic variables type will be resolved as "string", and you are trying to add string value to List of decimal, that`s why run-time will throw exception.

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


What you are trying to do:
Simply add following lines in your IDE, the compile time error will be displayed.

List<decimal> dl = new List<decimal>();
dl.Add("Hello");

Upvotes: 1

Samer Adra
Samer Adra

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

Related Questions