Cast
In this chapter you will learn:
Change data type with cast
using System;/*from ja va 2s. c o m*/
using System.Linq;
public class MainClass{
public static void Main(){
object[] doubles = {1.0, 2.0, 3.0};
IEnumerable<double> d = doubles.Cast<double>();
Console.Write(d);
}
}
Cast to int
using System;/*from j a v a 2s .c om*/
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
ArrayList classicList = new ArrayList(); // in System.Collections
classicList.AddRange(new int[] { 3, 4, 5 });
IEnumerable<int> sequence1 = classicList.Cast<int>();
foreach (int i in sequence1)
{
Console.WriteLine(i);
}
}
}
The output:
Cast and catch exception
When encountering an incompatible type Cast throws an exception;
using System;// j a va2 s . c o m
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
ArrayList classicList = new ArrayList(); // in System.Collections
DateTime offender = DateTime.Now;
classicList.Add(offender);
IEnumerable<int> sequence1 = classicList.Cast<int>(); // Throws exception
foreach (int i in sequence1)
{
Console.WriteLine(i);
}
}
}
The output:
Next chapter...
What you will learn in the next chapter:
Home » C# Tutorial » Linq Operators