Example:
System.Web.Security.MembershipCollection
implements IEnumerable
and not IEnumberable<T>
. Why doesn't it implement the latter, when it seems that it would be better (e.g. use LINQ)?
Or, is it not necessarily better?
Cannot Create Arrays of Parameterized Types. Cannot Create, Catch, or Throw Objects of Parameterized Types. Cannot Overload a Method Where the Formal Parameter Types of Each Overload Erase to the Same Raw Type.
Type safety. Generics shift the burden of type safety from you to the compiler. There is no need to write code to test for the correct data type because it is enforced at compile time. The need for type casting and the possibility of run-time errors are reduced.
We can have generic methods in both generic types, and in non-generic types. Our first example in Program 43.1 is the generic method ReportCompare in the non-generic class StringApp . ReportCompare is a method in the client class of String<T> which we encountered in Section 42.4.
Advantages of using generics Generics allow the programmer to use the same method for Integer arrays, Double arrays, and even String arrays. Another advantage of using generics is that Individual typecasting isn't required. The programmer defines the initial type and then lets the code do its job.
History matters. Generics didn't always exist, so you may encounter classes and APIs that were designed before the advent of generics.
Also, target audience matters. Some features are targeting a developer audience that may have problems understanding generics:
Tradeoff: APIs using some advanced features of Generics may be too difficult to use for some developers. The concept of Generics is not widely understood, in some cases the syntax may pose problems, and as any large new feature, Generics may pose a significant learning curve for some entry-level developers.
Yes, the quote is from 2004, but some, if not most of the .Net API you use today came out in 2005, so the quote is actually very relevant.
You can use LINQ with any IEnumerable
by using the Cast<T>()
function or the OfType<T>()
function. If you're confident that the IEnumerable
only contains objects of a particular type, then Cast<T>()
will be slightly faster.
For example,
ArrayList foo = new ArrayList();
foo.Add("bar");
foo.Add("baz");
var bar = foo.Cast<string>().Select(s => s.ToUpper());
There are many existing classes (like ArrayList
) that existed before the advent of generics in .NET, so they are still non-generic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With