Reputation: 4077
I am working on a WCF service in which the objects are defined as below :-
public class Test1
{
public string s {get;set;}
public string a {get;set;}
}
public class Test2
{
public string u {get;set;}
public string v {get;set;}
}
public class ABC : List<Test1>
public class DEF: List<Test2>
public class Test
{
public ABC x {get;set;}
public DEF y {get;set;}
}
The code that raised the exception was (assuming that result is an instance of class ABC) :-
return result.OrderBy(i=>i.s).ThenBy(j=>j.a);
The above code threw me an InvalidCastException on runtime. I am assuming that this happened because OrderBy returned an IOrderedEnumerable and so, it was unable to cast it. I tried various variations of the above code :-
return (ABC)result.OrderBy(i=>i.s).ThenBy(j=>j.a);
return (ABC)result.OrderBy(i=>i.s).ThenBy(j=>j.a).ToList();
None worked. So, I changed the Test class to following :-
public class Test
{
public List<T> x {get;set;}
public List<T> y {get;set;}
}
So, everything is working fine now. I read somewhere that we should not use List in public APIs. However, does that apply to WCF also ? And, is this approach correct or should I try to inherit ABC and DEF class from Collection<T>
?
Upvotes: 1
Views: 149
Reputation: 3322
This will cause an InvalidCastException
List<Test1> test1 = new List<Test1>();
ABC abc = (ABC)test1;
This will not
List<Test1> test1 = new ABC();
ABC abc = (ABC)test1;
What you are doing is the equivalent of the first one. There may be better ways but one solution would be to add a constructor to ABC that takes an IEnumerable.
public class ABC : List<Test1>
{
public ABC(IEnumerable<Test1> enumerable)
{
if (enumerable != null)
this.AddRange(enumerable);
}
}
Then change your return statement to look like this.
return new ABC(result.OrderBy(i=>i.s).ThenBy(j=>j.a));
Upvotes: 2
Reputation: 152624
should I try to inherit ABC and DEF class from
Collection<T>
Only if ABC
and DEF
offer functionality above what List<T>
provides. Even then, extension methods may be more appropriate.
But it's unclear why you're getting an InvalidCastException
- You need to add the code that gives you that exception to know what a proper solution is.
Upvotes: 0