Convert Anonymous Class to Object in C#

In C#, an anonymous class is a temporary class created to store data temporarily. If you need to convert an anonymous class into an object class, you can do so by creating a new object class and assigning the property values of the anonymous class to the object class.

For example, if there is an anonymous class called Student that has properties Name and Age, it can be converted into an object class called StudentObject as shown below:

var student = new { Name = "Alice", Age = 20 };

public class StudentObject
{
    public string Name { get; set; }
    public int Age { get; set; }
}

StudentObject newStudent = new StudentObject
{
    Name = student.Name,
    Age = student.Age
};

In this way, the anonymous class has been successfully converted into an object class. It is important to ensure that the property names of the anonymous class match those of the object class during the conversion process to avoid compilation errors.

bannerAds