Referencing System.Type?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ceestand
    New Member
    • Mar 2007
    • 8

    Referencing System.Type?

    I'm trying to make a change to an object depending contextually on it's type. The following code, even though I pass the Int32 into the function as an Object, still knows it's an Int32.
    Code:
    public String FunctionName(Object obj)
    {
    return obj.GetType().ToString();
    }
    
    Int32 testObj = 0;
    FunctionName(testObj);
    //returns "System.Int32"
    However, the following gives me a compile-time exception:
    Code:
    public void FunctionName(ref Object obj)
    {
    Type typ = obj.GetType();
    Object x = 0;
    obj = (typ)x;
    }
    Even if I replace the typ object with System.Int32, I still get an error saying I can't cast Object to Int32. Maybe someone out there knows:

    Why won't it let me compile this and just give me an exception at runtime if the cast isn't valid?

    Is there a way for me to get a handle on a specific System.Type? For instance, I can pass "System.Int 32" into a generic function, but the following won't work:
    Code:
    public T SomeFunction<T>()
    {...}
    Type typ = Type.GetType(Int32);
    SomeFunction<typ>();
  • Plater
    Recognized Expert Expert
    • Apr 2007
    • 7872

    #2
    I think if you use the "ref" keyword you cannot convert it?
    I would not expect you to be able to type cast to a variable type like that, but you should be able to like switch on the object's actual type.

    Comment

    Working...