Howdy, Stranger!

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

Sign In with Facebook Sign In with Google Sign In with OpenID

Categories

We have migrated to a new platform! Please note that you will need to reset your password to log in (your credentials are still in-tact though). Please contact lee@programmersheaven.com if you have questions.
Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

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.