0

I am having a HotDog class as a child of Food class.

public class HotDog : Food
{
    public HotDog () : base ("hotdog", new string[] { "bread", "meat"}, new int[] { 1, 1 }, 0.7)
    {
    }
}

I tried to do this

Type t = typeof("HotDog");
if (t is Food) {
    Food f = (Food)Food.CreateOne (t);
}

This is my CreateOne method

public static Consumables CreateOne (Type t)
{
    return (Consumables)Activator.CreateInstance (t);
}

But I got the error that t is never of the provided Food type so the code inside is unreachable. Any idea what's wrong with this thing and how can I fix it?

Tree Nguyen
  • 1,198
  • 1
  • 14
  • 37

3 Answers3

3

Have you tried

 Type t = typeof(HotDog)

See also Type Checking: typeof, GetType, or is?

Community
  • 1
  • 1
Reuben Mallaby
  • 5,740
  • 4
  • 47
  • 45
1

You need Reflection to get this to work.

First get the actual type HotDog:

Type t = Type.GetType("MyNamespace.HotDog");

Now create a new instance of this type:

HotDog instance = (HotDog) Activator.CreateInstance(t);

Note that this will call the default-constructor. If you need a parameterized one use Activator#CreateInstance(t, object[]) instead.

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
  • Why use reflection out here when types can be directly accessed, created and invoked – Mrinal Kamboj Oct 08 '14 at 06:41
  • Well, it also works without Type.GetType thats true, but anyway its Reflection when you use the Activator... However I concentrated on the OPs post itself where he´s using a string to get the actual type. – MakePeaceGreatAgain Oct 08 '14 at 06:47
  • The problem is because HotDog is a kind of Food so I want to try if (t is Food). But it never returns true! – Tree Nguyen Oct 08 '14 at 06:49
0

As far as I can see it the problem is your if-statement.

Type t = typeof(...);
if (t is Food) { ... }

The is operator checks whether the type of the left expression is a valid value of the right expression.

In other words you are checking if the type of t (which is Type) is a valid value for the Food class, which of course it isn't.

What you can do is to use Type.IsAssignableFrom:

if (typeof(Food).IsAssignableFrom(t)) { ... }

IsAssignableFrom determines whether an instance of the type t can be assigned to a variable of type typeof(Food), i.e. if it returns true you can do

Hotdog h;
Food f;

if (typeof(Food).IsAssignableFrom(typeof(Hotdog))
{
    f = h; // you can assign a Hotdog to a Food
}

// this would return false for your classes
if (typeof(Hotdog).IsAssignableFrom(typeof(Food))
{
    h = f; // you can assign a Food to a Hotdog
}
Dirk
  • 10,668
  • 2
  • 35
  • 49