What is the output of this C# code snippet?
using System; class Program { static void Main() { dynamic d = "hello"; string s = "hello"; Console.WriteLine(d.ToUpper()); Console.WriteLine(s.ToUpper()); } }
Both dynamic and static strings call the same method, but dynamic resolution happens at runtime.
Both d.ToUpper() and s.ToUpper() call the ToUpper method on a string, which returns the uppercase version. The output is HELLO twice.
Consider this code measuring elapsed time for 1 million calls. What is the expected output pattern?
using System; using System.Diagnostics; class Program { static void Main() { dynamic d = "test"; string s = "test"; Stopwatch sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 1000000; i++) { var x = d.ToUpper(); } sw.Stop(); Console.WriteLine("Dynamic: " + sw.ElapsedMilliseconds); sw.Restart(); for (int i = 0; i < 1000000; i++) { var y = s.ToUpper(); } sw.Stop(); Console.WriteLine("Static: " + sw.ElapsedMilliseconds); } }
Dynamic calls resolve method at runtime, adding overhead.
Dynamic calls use runtime type resolution, which is slower than static calls resolved at compile time. So dynamic calls take more time.
What error does this code produce when run?
using System; class Program { static void Main() { dynamic d = 10; Console.WriteLine(d.ToUpper()); } }
Check if the type supports the called method.
The integer type does not have a ToUpper method. Dynamic invocation tries to call it at runtime and fails with a RuntimeBinderException.
Which explanation best describes why dynamic type resolution in C# adds runtime cost?
Think about what happens behind the scenes when you use dynamic.
Dynamic variables cause the compiler to emit code that performs type checks and method lookups at runtime, which adds overhead compared to static calls resolved at compile time.
What is the output of this C# program?
using System; class Base { public virtual string GetName() => "Base"; } class Derived : Base { public override string GetName() => "Derived"; } class Program { static void Main() { Base b = new Derived(); dynamic d = new Derived(); Console.WriteLine(b.GetName()); Console.WriteLine(d.GetName()); } }
Remember how virtual methods behave with static and dynamic calls.
Both static and dynamic calls invoke the overridden method in Derived. So both print "Derived".