So I’ve got a class like this:
public class A { internal A(int i) { ... } public int Foo { get; set; } }
This class is then inherited by a bunch of generated classes, eg:
public class B : A { ... }
The int based constructor isn’t exposed to the inherited class (for design reasons I don’t want it exposed). In my library which holds the definition for class A I’ve got a method like this:
public T Load<T>() where T : A { //do some stuff, create an instance of T from an int, then return it }
And then I’d use it like this:
B b = Helper.Load<B>();
Since the constructor I want to use isn’t exposed to class B when I do typeof(T).GetConstructor(typeof(int)) I don’t get the constructor back, so I want thinking that I’d do this:
return (T)new A(/*some int */);
But that gives me a runtime error System.InvalidCastException, that I can’t cast a type A to type B.
How do I go about achieving this upcasting?
You can just use default constructors so you can instantiate objects of type T with the new() constraint. Then class A can have a virtual (or abstract to your liking) method that takes an int as an argument and initializes the object after the constructor has run.
If you intend some sort of factory pattern, you don’t need to hesitate initializing parts of an object outside the constructor call as long as it is done before you return the object to the caller’s control.