2

I have a class called Resource, this is inherited by a class called ResourceMeta

I need to upcast ResourceMeta to Resource without it still thinking it is a type of ResourceMeta.

When I try to save my object using entity framework, it will complain about mappings not existing, rightly so because it will be trying to save ResourceMeta rather than Resource.

I've tried (Resource)resourceMeta however this still retains the type of ResourceMeta just limits the properties available to Resource.

Rui Jarimba
  • 11,166
  • 11
  • 56
  • 86
asleep
  • 4,054
  • 10
  • 34
  • 51
  • Assuming Resource is a superclass of ResourceMeta (class ResourceMeta: Resource), casting from ResourceMeta to Resource would be upcasting, not downcasting. – TheFogger Sep 15 '10 at 12:12

3 Answers3

3

That is not possible, you can't change the actual type of an object.

To get a Resource object from a ResourceMeta object, you have to create a new Resource object using the data from the ResourceMeta object.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • @Shahin: Yes, it's possible to hack an object to think that it's a different object, but this can easily blow up. For example, the garbage collector occationally moves object in memory, and if it moves an object thinking that it is a different type, it could corrupt other objects, or the memory management itself. – Guffa Sep 15 '10 at 12:56
0

Not possible in simple words , you need to create a new instance of Resource and then return

TalentTuner
  • 17,262
  • 5
  • 38
  • 63
0

Is inheritance the correct representation of the association between ResourceMeta and Resource instances. If not, you could favor composition instead of inheritance and in this way when you want to save the resource instance you could just do resourceMetaInstance.Resource.

João Angelo
  • 56,552
  • 12
  • 145
  • 147