1

I have defined my extended class this way:

public class ExtendedAttributeMetadata : AttributeMetadata
{
    public bool IsTwoOption { get; set; }
}

But upon copying the source array of type AttributeMetadata[] to my new destination array ExtendedAttributeMetadata[], i am getting InvalidCastException:

"At least one element in the source array could not be cast down to the destination array type."

Code:

AttributeMetadata[] attributes;
//...
ExtendedAttributeMetadata[] extendedAttributes = new ExtendedAttributeMetadata[attributes.Length];                
attributes.CopyTo(extendedAttributes, 0);

ADDED:

Where AttributeMetadata is derived from MetadataBase

public class AttributeMetadata : MetadataBase

And MetadataBase is an abstract class.

public abstract class MetadataBase : IExtensibleDataObject

Please suggest the best and optimal way of copying in my case.

3
  • Where did the original array come from? It seems pretty clear that at least one of the elements of the original array is not of type ExtendedAttribute. Commented Jun 16, 2013 at 7:08
  • Original array is of type Attribute[] from which i have extended my class. Commented Jun 16, 2013 at 7:15
  • 1
    Your edits don't change anything: you're trying to copy an object that is not of type ExtendedAttributeMetadata into an array of type ExtendedAttributeMetadata. That just isn't possible. Commented Jun 16, 2013 at 7:39

2 Answers 2

1

You could not copy a base class to derived class so you must be generate it:

var extendedAttributes = 
   attributes.Select(p=>new ExtendedAttribute{IsTwoOption=true/false}).ToArray();
Sign up to request clarification or add additional context in comments.

Comments

0

Is the list of attributes just the AttributeMetadata abstract base class?

You are getting that error because there are Attributes in the list that are not of type ExtendedAttributeMetadata

you can filter these out with a linq statement:

var extendedAttributes = attributes.OfType<ExtendedAttributeMetadata>().ToArray();

1 Comment

the OfType<> filter should still work if you replace ExtendedAttribute with ExtendedAttributeMetadata.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.