Home > Backend Development > C++ > How Can I Cast an Object to an Anonymous Type in C#?

How Can I Cast an Object to an Anonymous Type in C#?

Linda Hamilton
Release: 2025-01-05 22:46:40
Original
148 people have browsed it

How Can I Cast an Object to an Anonymous Type in C#?

Cast to Anonymous Type

The question is how to cast an object to an anonymous type. Anonymous types are created using object initializers and are often used as a convenient way to store data. However, they do not have a type name, which can make it difficult to cast them.

One way to cast an object to an anonymous type is to use a trick that involves using a dummy value of the desired anonymous type. This dummy value is used to infer the type of the object to be cast. Here is an example:

public class Program
{
    public static void Main(string[] args)
    {
        var a = new { Id = 1, Name = "Bob" };
        TestMethod(a);
    }

    private static void TestMethod(object x)
    {
        // This is a dummy value, just to get 'a' to be of the right type
        var a = new { Id = 0, Name = "" };
        a = Cast(a, x);
        Console.WriteLine(a.Id + ": " + a.Name);
    }

    private static T Cast<T>(T typeHolder, object x)
    {
        // typeHolder above is just for compiler magic
        // to infer the type to cast x to
        return (T)x;
    }
}
Copy after login

Another way to cast an object to an anonymous type is to use a generic extension method. This method can be used to cast an object to any anonymous type. Here is an example:

public static class AnonymousTypeExtensions
{
    public static T CastTo<T>(this object value, T targetType)
    {
        // targetType above is just for compiler magic
        // to infer the type to cast value to
        return (T)value;
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        var a = new { Id = 1, Name = "Bob" };
        var b = a.CastTo(new { Id = 0, Name = "" });
        Console.WriteLine(b.Id + ": " + b.Name);
    }
}
Copy after login

However, it is important to note that using anonymous types in this way can be tricky and is not recommended in general. It is better to use a real type instead.

The above is the detailed content of How Can I Cast an Object to an Anonymous Type in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template