简体   繁体   中英

How to typecast any object to the actual type

Is there way to typecast an object to some specific type at runtime? Is it possible at all?

public static void TryTypeCasting(object obj)
{
    Type type = obj.GetType();
    // Can I use this "type" variable somehow to typecast "obj" to its actual type?
}

I am using C# 4.0.


EDIT 1:

Thanks all for your inputs.

I may be trying to achieve something impossible. But I posted this question in order to get views of experts on this and to know if something like this is made achievable in C# 4.0.

Here is a real time problem:

In our product, our client side API (method) serializes instance of "some" class (say Employee ) that derives from our entity class called Person . That serialized instance (ie string value) is sent to the server side API (a method which has responsibility to de-serialize string to appropriate class's instance) through some intermediate classes. So, on the server side, only thing that API gets is a string.

However while serializing, custom serializer always add fully qualified name of the class (whose instance is being serialized) as the first line of the resulting output. So on server side, while reading the first line, I know the class (ie Employee in this case) to which the string should be de-serialized.

Further, we call a web service method ( which I am not allowed to change ) that accepts an argument of type Person .

Now, after deserialization at this stage, I have an instance of Employee stored in a variable of type object . But even though instance is available, I cannot pass it as an argument until I typecast it to Employee . How can I achieve this?

Sample code is provided here:

 public static void Deserialize(string serializedObject)
        {
            StringReader stringReader = new StringReader(serializedObject);

            // Read the first line to know class and assembly details
            string firstLine = stringReader.ReadLine();
            string[] assemblyAndClassDetails = firstLine.Split(new[] { ',' }, StringSplitOptions.None);
            string className = assemblyAndClassDetails[0];
            string assemblyName = assemblyAndClassDetails[1];

            // Remove the first line before passing it to the serializer
            serializedObject = serializedObject.Remove(0, firstLine.Length);

            // Know the type of the serialized instance
            Type typeToBeDeserializedTo = Type.GetType(className);

            DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeToBeDeserializedTo);
            using(MemoryStream memoryStream = new MemoryStream(Encoding.ASCII.GetBytes(serializedObject)))
            {
                memoryStream.Position = 0;
                object deserializedObject = dataContractJsonSerializer.ReadObject(memoryStream);

                // NOW I WANT TO call a method that accepts an argument of type `Person` How can I do this?
            }
        }

No, this is entirely impossible (unless of course the specific type is known at compile time, in which case you can eg hardcode a cast).

It could never be any other way, since type casting means that the compiler has full knowledge of what the type of the result is. How would it be possible for the compiler to have knowledge of something that can only be determined at runtime?

Whenever this question comes up (and it does every so often), the answer is "there is probably an appropriate solution for your situation that involve neither this hypothetical type of cast nor reflection". If you state your case in more detail we could suggest such a solution.

You can't do this at runtime, because you don't know the actual type of the object. This information is known only at runtime, not at compile-time.

Say you could assign your object to a variable of the correct type (which I'm not sure is possible), you still cannot write any code against it within the method, as the compiler will not know what the type is at compile time.

A few options would be:

  • declare overloads of your method that can deal with the possible types you would like to accept

  • try casting to the possible types within the method

    if ((var t1 = obj As type1) != null) Do something with t1

  • Use Generics

As other said, this is impossible.

But what about duck typing ?

((dynamic)yourObject).SomeMethod();

Type checking is delayed to execution of the code.

Pay attention to the fact that duck typing in a strongly-typed language like C# should be used with caution and for a specific set of use cases. Don't replace strong typing by using dynamic keyword everywhere!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM