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
Newsletter
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

  • Mistaking Code Production for Engineering Progress: AI Productivity Myths Part 1
  • Building a Practical Cloud-Native Golden Path: A Guide to Kubernetes-Based Service Delivery, Self-Service, and Developer-Friendly Defaults
  • Introducing senro: A Pipeline Engine You Program in Go
  • Kafka With Spring Boot: Introduction

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
·
May. 31, 19 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
10.2K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • 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