-4

I am looking for a way to convert my class type into a specific object using a string or Type object. For instance see my below simple code snippet:

        int i = 10;
        Type t = i.GetType();
        string str = typeof(t) i;

It saying that t is a varialbe which cannot used as a type. My question is that is there anyway to do this thing?

Muhammad Faizan Khan
  • 10,013
  • 18
  • 97
  • 186

1 Answers1

-2

Here is an example of a cast and a convert:

using System;

public T CastObject<T>(object input)
{   
    return (T) input;   
}

public T ConvertObject<T>(object input) 
{
    return (T) Convert.ChangeType(input, typeof(T));
}
  • 1
    This does not answer the OP's question: they have a `Type` object, not a generic-type argument. Also, `Convert.ChangeType` is a very old and _effectively_ obsolete method from .NET 1.1 days (~2002) that should not be used by anyone because there is zero compile-time safety: i.e. it will let you compile a conversion that will always fail at runtime, so there are far better alternatives. – Dai Jul 06 '22 at 11:21
  • 2
    @Dai This was copied without attribution from the [accepted answer](https://stackoverflow.com/a/1145562/11683) of the duplicate. It does answer the OP's question, like specifically called out in the answer itself, between the *Edit* and the *Edit 2*. – GSerg Jul 06 '22 at 11:30
  • @GSerg But the OP in this question _doesn't have_ a type-variable (i.e. a generic type parameter, or type identifier), only a `String` or a `Type` object. – Dai Jul 06 '22 at 11:54
  • @Dai The OP in this question has `Type t`, and `Convert.ChangeType(value1, t)` accepts exactly that. – GSerg Jul 06 '22 at 12:55
  • @GSerg But _this answer_ hides `Convert.ChangeType` behind `ConvertObject(object input)` which does _not_ accept a `Type t` parameter. – Dai Jul 06 '22 at 13:47
  • @Dai Yes, which is rather unhelpful! But it then unhides it with a non-generic `Type intType = typeof(Int32);` in the second code block. – GSerg Jul 06 '22 at 13:49