{{announcement.body}}
{{announcement.title}}

Casting a C# Object From Its Parent

DZone 's Guide to

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.

· Web Dev Zone ·
Free Resource

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.

Topics:
web dev ,c# objects ,parent objects

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}