casting with a generic type - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

casting with a generic type

VanilleBertVanilleBert Posts: 29Member
Hi all,

I have a problem I can't express in english, so please look at the code and try to compile it.

[code]
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
// base class
class Class1
{
public bool castable;
public int ID;

public Class1(int id)
{
ID = id;
castable = false;
}
}

// based on Class1
class Class2 : Class1
{
public T Value; // value with no concrete type

public Class2(int id, T value)
: base(id)
{
Value = value;
castable = true;
}
}

class Program
{
static void Main(string[] args)
{
Random Random = new Random();
List TheList = new List();
for (int i = 0; i < 100; i++)
{
TheList.Add(new Class1(Random.Next(1000)));
TheList.Add((Class1)new Class2(Random.Next(1000), Random.Next(1000)));
TheList.Add((Class1)new Class2(Random.Next(1000), Random.NextDouble()));
}

foreach (Class1 c in TheList)
{
Console.Write(c.ID.ToString() + " ");
if (c.castable)
{ // This is wrong.
Class2 casted = (Class2)c; // TODO
// No idea how to go on.
Console.WriteLine(casted.Value.ToString());
}
else
{
Console.WriteLine("not castable");
}
}
Console.Read();
}
}
}
[/code]
Sign In or Register to comment.