0

I have an array of objects looking like this

public class ViewFilterData
{
    public string Table { get; set; }
    public string Field { get; set; }
    public string Value { get; set; }
}

Due to calling function in separate dll, I need to pass this array as object[]. The above class is defined in both sections.

Project compiles, however when I try to cast each object in the array to above class, I get an invalidCastException, indicating that it "magically" know the originally class and refuse to cast it to the new one even though they are verbatim identical. Do I need to use reflection and create a new class marshalling over the array object by object and attribute by attribute? Or is there a simpler faster way? Thought about using scructs, however would rather not if possible.

"Unable to cast object of type 'Original.ViewFilterData' to type SeparateDLL.ViewFilterData'."

I call the function like this

var dt = oRepository.Page((object[])oDataRequest.Filters.ToArray())

and define it like this

public DataTable Page(object[] Filters)
2
  • 1
    What you're trying to accomplish is called duck typing, and it doesn't work in C#. Even though both classes have the same set of properties, you can't cast instance of one of the classes to an instance of the other one. Commented Jun 24, 2014 at 23:57
  • If it's object[] you should be able to send yourtype[] without any casting Commented Jun 24, 2014 at 23:58

2 Answers 2

1

Same name doesn't mean, they're of the same types. .NET cannot magically infer that.

for small objects, just write a quick LINQ query:

var separateDllFilters = oDataRequest.Filters.Select(of => new SeparateDLL.ViewFilterData
{
 Table = of.Table,
 // so on
}).ToArray();

however, if all the fields are same, (or even if they're not) you can use tools like AutoMapper to transform them easily.

typically, this is the order of solutions:

  1. quick LINQ queries.
  2. Extension methods to map the types.
  3. Tools like AutoMapper

the solution you choose depends on factors like, how often you do this, how many callers need this, etc.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, adding above code before calling the separate dll worked.
0

The above class is defined in both sections.

This is not valid in C#, each class is distinct from all other classes.

If you want to pass data between libraries you must use consistent types. The most popular method is to use a base library.

Comments

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.