-2

As the title states, is it possible to upcast/clone a base class into an extending class without knowing the internal structure of the base class?

As an example, given a match object with with named groups, I would like to subclass the match class into a new class NamedGroupMatch with properties that point to the named groups. So given a match instance, I am curious whether it is possible to upcast/clone this instance into an instance of NamedGroupMatch.

I am fully aware that I can accomplish this with composition, and that is beside the point.

Non functioning code example illustrating intent:

class NamedGroupMatch : System.Text.RegularExpressions.Match
{
     public Group NamedGroup1 {get; set;}
     public Group NamedGroup2 {get; set;}

     public NamedGroupMatch(Match match)
     {
         //initialize this instance to be a clone of the match instance parameter
     }
}


var regex = new Regex("pattern");
var match = regex.Match("some string with named groups");

//instead of working with a match instance, 
//we would like to work with a NamedGroupMatch instance 
//as it is logically an extension of a match object and should
// have all of the same properties. 
var ngMatch = new NamedGroupMatch(match);
cubesnyc
  • 1,385
  • 2
  • 15
  • 32
  • If you upcast to an invalid type, you will get an `InvalidCastException` – Emanuel Vintilă Mar 09 '20 at 22:12
  • Can you please provide sample (even if not compilable) code that illustrates what you want? You've used cast/clone/subclass which are very different things... I feel that you are looking for magically created constructor `Derived(Base base)`, but I could be totally wrong. – Alexei Levenkov Mar 09 '20 at 22:58
  • @AlexeiLevenkov yes, essentially, unless there is some other way to do it. – cubesnyc Mar 09 '20 at 23:37

1 Answers1

1

If I understand you correctly, there is nothing that keeps you from implementing such a constructor. It would be convenient to have a copy constructor in the base class which you could then call in the constructor of the derived class to initialize all fields in the base class properly. The additional information in the derived class would have to be set manually to some default, obviously.

But it is, as Alexei pointed out in a comment, not provided by the language. That would also be hard to do since it would not be clear how to initialize members which are not in the base class.

Remember that C# does not even, as opposed to C++, default-define a copy constructor with an argument of the same type.

Peter - Reinstate Monica
  • 15,048
  • 4
  • 37
  • 62