I'm working on some code which uses dynamic variables.
dynamic variable;
Behind scenes, this variable contains collection of Shapes which is again collection of dynamic variables. So code like this working fine:
foreach(var shape in variable.Shapes) //Shapes is dynamic type too
{
double height = shape.Height;
}
I need to get first item height from this collection. This hack works well:
double height = 0;
foreach(var shape in variable.Shapes)
{
height = shape.Height; //shape is dynamic type too
break;
}
Is there better way to accomplish this?
In C#, you can access dynamic properties by obtaining a PropertyObject reference from the specific object reference using the AsPropertyObject method on the object.
Dynamic Variable Overview The distinguishing characteristic of a dynamic variable is that its value can change while the application runs. For example, your application might maintain a threshold value that is compared to a field value in each tuple processed.
In C# 4.0, a new type is introduced that is known as a dynamic type. It is used to avoid the compile-time type checking. The compiler does not check the type of the dynamic type variable at compile time, instead of this, the compiler gets the type at the run time.
Dynamic variables compute their own values by executing statements and logical expressions. A dynamic variable assigns itself the result of a calculation or operation. The dynamic variable types are dynamic string, dynamic number, and dynamic True/False (Boolean).
Because variable
is dynamic
, you won't be able to evaluate variable.Shapes.First()
, since determination of extension methods occurs at compile time, and dynamic invocation occurs at runtime. You will have to call the static method explicitly,
System.Linq.Enumerable.First<TType>(variable.Shapes).Height
.
Where TType
is the expected type of the items in the enumerable.
Otherwise, use LINQ as others have suggested.
You can use the LINQ
method First()
or FirstOrDefault()
to get the first item.
First() - Returns the first element of a sequence.
FirstOrDefault() - Returns the first element of a sequence, or a default value if the sequence contains no elements.
using System.Linq;
double height = 0;
// this will throw a exception if your list is empty
var item = System.Linq.Enumerable.First(variable.Shapes);
height = item.Height;
// in case your list is empty, the item is null and no exception will be thrown
var item = System.Linq.Enumerable.FirstOrDefault(variable.Shapes);
if (item != null)
{
height = item.Height;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With