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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • 5 Advantages of Dart Over JavaScript, Python, and Bash
  • Automating Cucumber Data Table to Java Object Mapping in Your Cucumber Tests
  • Specification by Example Is Not a Test Framework
  • What Is API-First?

Trending

  • Testing SingleStore's MCP Server
  • What Is Plagiarism? How to Avoid It and Cite Sources
  • Debugging With Confidence in the Age of Observability-First Systems
  • How to Format Articles for DZone
  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
9.5K 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, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • 5 Advantages of Dart Over JavaScript, Python, and Bash
  • Automating Cucumber Data Table to Java Object Mapping in Your Cucumber Tests
  • Specification by Example Is Not a Test Framework
  • What Is API-First?

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!