How to use a .NET Type in a cast

62 Views Asked by At

Suppose a method is passed a Type. How can it be used in a cast or the right side of keyword as.

Document... System.Type

    internal static void Test2()
    {
        Computer c0 = new Computer("Model Z", 123);
        Computer c1 = new Computer("Model Z", 456);
        Debug.Assert(c0.Equals(c1));
        object o0 = c0;
        object o1 = c1;
        Debug.Assert(o0.Equals(o1) == false);
        Debug.Assert((o0 as Computer).Equals(o1 as Computer));
        Debug.Assert(((Computer)o0).Equals((Computer)o1));

        Type t = typeof(Computer);
        //Debug.Assert((o0 as t).Equals(o1 as t));
        //Debug.Assert(((t)o0).Equals((t)o1));
        Console.WriteLine("END Test2.");
    }


internal class Computer
{
    private string Description { get; set; }
    private int SerialNumber { get; set; }
    internal Computer(string d, int sn) { this.Description = d; this.SerialNumber = sn; }
    internal bool Equals(Computer other)
    {
        return this.Description.Equals(other.Description);
    }
}
1

There are 1 best solutions below

0
On BEST ANSWER

System.Type is a runtime construct/representation of a type. Casting is a compile-time construct. Basically you are informing the compiler how you want to interpret the memory. So what you are asking is not possible.

If you truly want to have a method take a type, consider using generics.

void SomeThing<T>(...)
{
   var t = something as T;
}