In the chapter Generics CLR Via C# v3, Jeffrey Richter says below TypeList<T>
has two advantages
- Compile-time type safety
- boxing value types
over List<Object>
, but how is the Compile-time type safety is achieved?
//A single instance of TypeList could hold different types.
using System;
using System.Collections.Generic;
using System.Text;
namespace MyNamespace
{
namespace Generics
{
class Node
{
private Node next_;
public Node(Node next) {
next_ = next;
}
public Node getNext() {
return next_;
}
}
internal sealed class TypeList<T> :Node
{
T data_;
public T getData() {
return data_;
}
public TypeList(T data, Node next):base(next) {
data_ = data;
}
public TypeList(T data):this(data,null) {
}
public override String ToString()
{
return data_.ToString() + (base.getNext() != null ? base.getNext().ToString() : string.Empty);
}
}
class Dummmy:Object
{
public override String ToString() {
return "Dummytype".ToString();
}
}
class Program
{
static void Main(string[] args)
{
Dummmy dummy = new Dummmy();
Node list = new TypeList<int>(12);
list = new TypeList<Double>(12.5121, list);
list = new TypeList<Dummmy>(dummy, list);
Double a = ((TypeList<Double>)list).getData();//Fails at runTime invalid cast exception
Console.WriteLine(list.ToString());
Console.Write("sds");
}
}
}
}