Sayid
Sayid

Reputation: 1103

How to pass class Type to a function to cast it in the function

At compile time, I don't know what exact type I will pass to a method, but I am sure that this type will contain some property. How can I pass a Type to a function to perform casting in the function? I would like to get something like that:

foo (classType cl)
{
    int x = ((cl)SomeClass).Id.Value;
}

Upvotes: 3

Views: 4619

Answers (3)

Asif Mushtaq
Asif Mushtaq

Reputation: 13150

Update

foo <T>() : where SomeTypeHavingValue
{
  int x = ((T)SomeClass).Value;
}

Upvotes: 1

Charleh
Charleh

Reputation: 14002

The other answer won't work when using .id because your T type isn't constrained. The class has no idea that any T could implement a field/property called id

Imagine you used instead

foo <int>()

T would be int and int doesn't have an id field/property

You can constrain though

foo <T>()
  where T : ClassTypeThatImplementsId
{
  int x = ((T)SomeClass).Value;
}

Though this means that T can only be of that particular type. Is there a base class that has ID that you can use instead? I don't know if this is the solution you want though...

Edit:

In response to your post:

foo <T>()
  where T : BaseClass
{
  int x = ((T)SomeClass).Value;
}

Should work assuming BaseClass implements 'Value' (and assuming SomeClass comes from somewhere as there appears to be no reference to it in the method!)

Upvotes: 5

Peter
Peter

Reputation: 14108

Something like this will work (if it is this you are trying to achieve), but you don't need casting:

public interface IHasInteger
{
    int Value { get; }
}

public class HasInteger : IHasInteger
{
    public int Value { get { return 1; } }
}

public class AlsoHasInteger : IHasInteger
{
    public int Value { get { return 2; } }
}

class Program
{
    static void Main(string[] args)
    {
        var a = new HasInteger();
        var b = new AlsoHasInteger();
        var c = new object();
        Console.WriteLine(GetInteger(a));
        Console.WriteLine(GetInteger(b));
        Console.WriteLine(GetInteger(c));
        Console.ReadLine();
    }

    private static int GetInteger(object o)
    {
        if (o is IHasInteger)
        {
            int x = ((IHasInteger)o).Value;
            return x;
        }

        return 0;
    }
}

Upvotes: 2

Related Questions