Cast Operator with Anonymous Types

Below is a sample sourecode that demonstrates the usage of the Cast Operator when using the anonymous type

Cast Operator with Anonymous Types

using System;

using System.Collections.Generic;

using System.Data;

using System.Linq;

namespace AbundantCode

{

internal class Program

{

//Cast Operator with Anonymous Types

private static void Main(string[] args)

{

var NumericValues = new object[] { "AbundantCode", 1, "765" };

foreach (var Number in NumericValues.Cast<int>())

Console.WriteLine(Number);

Console.ReadLine();

}

}

}

When the element within the List cannot be converted to the target type, you will receive an exception “InvalidCastException”.

Cast Operator with Anonymous Types