Malboma99 Malboma99 - 1 month ago 5
C# Question

How can I downcast an instance generated by static method?

I have a problem with a C# program whose codes are like this :

class Program
{
static void Main(string[] args)
{
Child childInstance = Child.ParseFromA(@"path/to/Afile") as Child;
}
}

class Parent{
int property;

public static Parent ParseFromA(string filename)
{
Parent parent = new Parent();
// parse file and set property here...
return parent;
}
}

class Child : Parent
{
public void SomeAdditionalFunction() { }
}


When running this code,
childInstance
becomes
null
.

I tried below assignment with explicit cast, but ended with an exception :

Child childInstance = (Child)Child.ParseFromA(@"path/to/Afile");


Since I want to parse some types of files into
Parent
and
Child
instance, I want to keep the design that generates instances by static methods.

How should I get proper
childInstance
?

Answer

You cannot downcast it. Once an object has been created as a Parent, it will always be a Parent. It's like trying to downcast an Animal to a Cat: That just won't work, since the Animal might in fact be a Dog.

Thus, your only solution is to create the correct object. The only option I see in your case is to make your static method generic:

public static T ParseFromA<T>(string filename) where T : Parent, new()
{
    T t = new T();
    // parse file and set property here...
    return t;
}

Usage:

Child childInstance = Parent.ParseFromA<Child>(@"path/to/Afile");

The generic constraint T : Parent ensures that T is a subtype of Parent, and new() ensures that T has a parameterless constructor.