DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • 5 Advantages of Dart Over JavaScript, Python, and Bash
  • The LLM Selection War Story: Part 1 - Why Your Model Selection Process is Fundamentally Broken
  • Developer Tools That Actually Matter in 2026
  • Automating Cucumber Data Table to Java Object Mapping in Your Cucumber Tests

Trending

  • Run Gemma 4 on Your Laptop: A Hands-On Guide to Google's Latest Open Multimodal LLM
  • Zero-Downtime Deployments for Java Apps on Kubernetes
  • Building a Skill-Based Agentic Reviewer with Claude Code: A Practical Guide Using Skills.MD, MCP Servers, Tools, and Tasks
  • A Scalable Framework for Enterprise Salesforce Optimization: Turning Outcomes Into an Operating System
  1. DZone
  2. Coding
  3. Languages
  4. Casting a C# Object From Its Parent

Casting a C# Object From Its Parent

In this post, a C# expert shows how to get around this common problem in his favorite language.

By 
Paul Michaels user avatar
Paul Michaels
·
May. 31, 19 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
10.0K Views

Join the DZone community and get the full member experience.

Join For Free

Have you ever tried to do something akin to the following?

[Fact]
public void ConvertClassToSubClass_Converts()
{
    // Arrange
    var parentClass = new SimpleTestClass();
    parentClass.Property1 = "test";

    // Act
    var childClass = parentClass as SimpleTestSubClass;

    // Assert
    Assert.Equal("test", childClass.Property1);
}

This is a simple Xunit (failing) test. The reason it fails is because you (or I) am trying to cast a general type to a specific, and C# is complaining that this may not be possible; consequently, you will get null (or for a hard cast, you'll get an InvalidCastException).

Okay, that makes sense. After all, parentClass could actually be a SimpleTestSubClass2 and, as a result, C# is being safe because there's (presumably, I don't work for MS) too many possibilities for edge cases.

This is, however, a solvable problem; there are a few ways to do it, but you can simply use reflection:

public TNewClass CastAsClass<TNewClass>() where TNewClass : class
{

    var newObject = Activator.CreateInstance<TNewClass>();
    var newProps = typeof(TNewClass).GetProperties();

    foreach (var prop in newProps)
    {
        if (!prop.CanWrite) continue;

        var existingPropertyInfo = typeof(TExistingClass).GetProperty(prop.Name);
        if (existingPropertyInfo == null || !existingPropertyInfo.CanRead) continue;
        var value = existingPropertyInfo.GetValue(_existingClass);

        prop.SetValue(newObject, value, null);
    }

    return newObject;
}

This code will effectively transfer any class over to any other class.

If you'd rather use an existing library, you can always use this one. It's also open sourced on GitHib.

Object (computer science) Transfer (computing) Testing IT Library

Published at DZone with permission of Paul Michaels. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • 5 Advantages of Dart Over JavaScript, Python, and Bash
  • The LLM Selection War Story: Part 1 - Why Your Model Selection Process is Fundamentally Broken
  • Developer Tools That Actually Matter in 2026
  • Automating Cucumber Data Table to Java Object Mapping in Your Cucumber Tests

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook