How is Generic Covariance & Contra-variance Implemented in C# 4.0? - c#

I didn't attend PDC 2008, but I heard some news that C# 4.0 is announced to support Generic covariance and contra-variance. That is, List<string> can be assigned to List<object>. How could that be?
In Jon Skeet's book C# in Depth, it is explained why C# generics doesn't support covariance and contra-variance. It is mainly for writing secure code. Now, C# 4.0 changed to support them. Would it bring chaos?
Anybody know the details about C# 4.0 can give some explanation?

Variance will only be supported in a safe way - in fact, using the abilities that the CLR already has. So the examples I give in the book of trying to use a List<Banana> as a List<Fruit> (or whatever it was) still won't work - but a few other scenarios will.
Firstly, it will only be supported for interfaces and delegates.
Secondly, it requires the author of the interface/delegate to decorate the type parameters as in (for contravariance) or out (for covariance). The most obvious example is IEnumerable<T> which only ever lets you take values "out" of it - it doesn't let you add new ones. That will become IEnumerable<out T>. That doesn't hurt type safety at all, but lets you return an IEnumerable<string> from a method declared to return IEnumerable<object> for instance.
Contravariance is harder to give concrete examples for using interfaces, but it's easy with a delegate. Consider Action<T> - that just represents a method which takes a T parameter. It would be nice to be able to convert seamlessly use an Action<object> as an Action<string> - any method which takes an object parameter is going to be fine when it's presented with a string instead. Of course, C# 2 already has covariance and contravariance of delegates to some extent, but via an actual conversion from one delegate type to another (creating a new instance) - see P141-144 for examples. C# 4 will make this more generic, and (I believe) will avoid creating a new instance for the conversion. (It'll be a reference conversion instead.)
Hope this clears it up a bit - please let me know if it doesn't make sense!

Not that Jon hasn't already covered it, but here are some links to blogs and videos from Eric Lippert. He does a nice job of explaining it with examples.
https://blogs.msdn.microsoft.com/ericlippert/2007/10/16/covariance-and-contravariance-in-c-part-one/
The videos:
https://www.youtube.com/watch?v=3MQDrKbzvqU
https://www.youtube.com/watch?v=XRIadQaBYlI
https://www.youtube.com/watch?v=St9d2EDZfrg

Related

Why do .NET methods sometimes return general types instead of using generics and type constraints?

Consider, for example, the method:
public static Attribute GetCustomAttribute(this ParameterInfo element, Type attributeType);
defined in System.Reflection.CustomAttributeExtensions
Wouldn't it make more sense to define instead:
public static T GetCustomAttribute<T>(this ParameterInfo element, T attributeType) where T : Attribute;
And save the casting?
The non-generic method of retrieving custom attribute is from the old .NET days when generics weren't implemented.
For current and future coding, you can take advantage of CustomAttributeExtensions.GetCustomAttributes<T> - if you're coding using .NET 4.5 version and above -.
Sadly - or maybe actually - software has a sequential evolution. I mean, there was a time where generic weren't with us (.NET 1.0 and 1.1), and there's a lot of code base that's inherited from early .NET versions, and because of framework team prioritzation it seems like not every method that would be better using a generic parameter(s) has been already implemented.
About inherited code
#BenRobinson said in some comment here bellow:
The point I was making was that these extension methods were added in
.net 4.5 (all of them not just the generic ones) and extension methods
were added after generics so non generic extension methods of any kind
have nothing to do with backwards compatibility with .net 1.0/1.1.
I'm adding this to avoid confusion: don't understand inherited code in terms of Microsoft not changing the non-generic code base because of backwards compatibility with third-party code.
Actually, I'm pointing out that current .NET version itself has a lot of code inherited from early .NET versions, either if the intention of Microsoft is maintaining backwards compatibility with third-party code or not.
I assume or guess that .NET Framework Team has prioritized new base class library (BCL) and satellite frameworks additions and some of members coming from pre-generics era are still as is because the change isn't worth the effort, or we could discuss if it's worth the effort and they did design decision mistakes, but StackOverflow isn't a discussion board, is it?
There is indeed a an overload that is equivalent to your example, GetCustomAttribute<T>(ParameterInfo), however to call this method without nasty reflection, you need to know the type of T at compile time. If you only know the type of T at run time then the equivalent method is GetCustomAttribute(ParameterInfo, Type)
Generics was added to the C# language in version 2. I believe that attributes was in the language at version 1 or 1.1 (can't remember which, I think it was in version 1 but I could be wrong).
This means that even though they would have saved a lot of unnecessary casting by changing all methods to use generics instead, they could have broken backwards compatability. And breaking backwards compatability is bad™.
Edit:
Also, I just thought about one more reason.
If you are writing reflection code it's often quite a hassle to call a generic method via reflection (C# has a really stupid api for doing so...) so if you are writing reflection code then using the non-generic version is in many cases much easier than using the generic one.
Edit again:
Damn, Ben Robinson beat me to the reflection point by a minute! :)

What is IList used for?

I have already searched for it on MSDN and I read the definition that it is a non generic ....
but my problem is that i am not understanding what is its use and when to use it . So i hope that anyone can help me . Thanks .
In addition to the older code that doesn't know about generics, there are also a lot of cases where you know you have a list of data, but you can't know of what ahead of time. Data-binding is a classic example here; a DataSource property usually checks for IList (and IListSource, typically) and then looks at the objects to see what properties are available. It can't use generics in this case.
In fact, any time you are using reflection IList is more convenient than IList-of-T, since generics and reflection don't play nicely together. It can be done, but it is a pain. Unfortunately since IList-of-T doesn't derive from IList there are cases where this can fail - but it is a good 95% rule.
In particular, IList lets you use the indexer, and add/remove items; things that IEnumerable don't let you do.
Most app-level code (i.e. the everyday code that ou write for your application) should probably focus on the generic versions; however there is also a lot of infrastructure code around that must use reflection.
IList (non-generic version) is a leftover from C# version one, when we didn't have generics.
With C# 2 and .NET Framework 2.0, generics was added to the language and generic implementations of the collection types was added. Therefore, the non-generic versions was no longer needed, but they couldn't be removed from the framework, since it would make porting code from .NET 1.1 to 2.0 a pain.
Today, you almost always use IList<T>, the primary reason for IList to still be around is for reasons of backwards compatibility.
It is an interface that existed before generics were introduced in .NET 2.0.
It is there for backwards compatibility.
Use the generic version.
it is a interface , which is normally implemented by collection classes which is intended to provide list like method but in .net version less than 2.0 i.e. without generic introduction so if you are using framework version 1.0, 1.1 than you would see the usage of this IList

Are Hashtable objects still useful?

Has the System.Collections.Hashtable object become obsolete?
With the implementation and refinements in generics from C# v2 and v3, it's been a long time since I've found a Hashtable more appropriate than a generic Dictionary. Literally, I can't recall the last time I used Hashtable.
Just wondering if anyone else has found a case where a Hashtable is still appropriate or preferred for implementation and the basis for that decision -- ease of use, performance, collection size, object type, etc.
UPDATE: was meaning to limit this question to C#.
Aside from the obvious case where you must use a Hashtable in an existing API that expects one (such as languages that don't yet support generic types). You also may need to use them if you need to access them from COM. I believe that Hashtable is COM visible, whereas Dictionary is not.
Other than that, you generally want to use Dictionary<> because it avoids boxing (a performance hit) and provides type safety.
Hashtable's are still useful in the cases where you are dealing with a language, or version of a language, which does not support generic types.
EDIT
For C# 2.0 or higher, Hashtable is really only of useful for the following scenarios
You want to get the previous semantic of an IDictionary instance returning null vs. throwing in the case a key is not present in the table.
Dealing with a legacy API which exposes a Hashtable value
Hashstable is still useful as a general purpose map if you are stuck with C# 1.0 :)

Are default parameters bad practice in OOP?

Do default parameters for methods violate Encapsulation?
What was the rationale behind not providing default parameters in C#?
I would take this as the "official" answer from Microsoft. However, default (and named) parameters will most definitely be available in C# 4.0.
No, it doesn't affect encapsulation in any way. It simply is not often necessary. Often, creating an overload which takes fewer arguments is a more flexible and cleaner solution, so C#'s designer simply did not see a reason to add the complexity of default parameters to the language.
Adding "Another way to do the same thing" is always a tradeoff. In some cases it may be convenient. But the more syntax you make legal, the more complex the language becomes to learn, and the more you may wall yourself in, preventing future extension. (Perhaps they'd one day come up with another extension to the language, which uses a similar syntax. Then that'd be impossible to add, because it'd conflict with the feature they added earlier)
As has been noted, default parameters were not a prioritized feature, but is likely to be added in C# 4.0. However, I believe there were excellent reasons not to include it earlier (in 4.0, as I've understood it, itäs mostly to support duck typing styles of programming where default parameters increases type compatibility).
I believe excessive parameter lists (certainly more than 4-5 distinct parameters) is a code smell. Default parameters are not evil in themselves, but risk encouraging poor design, delaying the refactoring into more objects.
To your first question - no, it's exactly the same as providing multiple overloaded constructors. As for the second, I couldn't say.
Default parameters will be included in C# 4.0
Some reading material about it:
click
click
It also seems that the author of this post will publish an article in the near future on the 'why' MS chooses to implement default params in C#
Here is an answer why it's not provided in C#
http://blogs.msdn.com/csharpfaq/archive/2004/03/07/85556.aspx
One drawback with the default parameter implementation in C# 4.0 is that it creates a dependency on the parameters name. This already existed in VB, which could be one reason why they chose to implement it in 4.0.
Another drawback is that the default value depends on how you cast your object. You can read about it here: http://saftsack.fs.uni-bayreuth.de/~dun3/archives/optional-parameters-conclusion-treat-like-unsafe/216.html .

What are major differences between C# and Java?

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
I just want to clarify one thing. This is not a question on which one is better, that part I leave to someone else to discuss. I don't care about it.
I've been asked this question on my job interview and I thought it might be useful to learn a bit more.
These are the ones I could come up with:
Java is "platform independent". Well nowadays you could say there is the Mono project so C# could be considered too but
I believe it is a bit exaggerating. Why? Well, when a new release of Java is done it is simultaneously available on all platforms it supports, on the other hand how many features of C# 3.0 are still missing in the Mono implementation? Or is it really CLR vs. JRE that we should compare here?
Java doesn't support events and delegates. As far as I know.
In Java all methods are virtual
Development tools: I believe there isn't such a tool yet as Visual Studio. Especially if you've worked with team editions you'll know what I mean.
Please add others you think are relevant.
Update:
Just popped up my mind, Java doesn't have something like custom attributes on classes, methods etc. Or does it?
Comparing Java 7 and C# 3
(Some features of Java 7 aren't mentioned here, but the using statement advantage of all versions of C# over Java 1-6 has been removed.)
Not all of your summary is correct:
In Java methods are virtual by default but you can make them final. (In C# they're sealed by default, but you can make them virtual.)
There are plenty of IDEs for Java, both free (e.g. Eclipse, Netbeans) and commercial (e.g. IntelliJ IDEA)
Beyond that (and what's in your summary already):
Generics are completely different between the two; Java generics are just a compile-time "trick" (but a useful one at that). In C# and .NET generics are maintained at execution time too, and work for value types as well as reference types, keeping the appropriate efficiency (e.g. a List<byte> as a byte[] backing it, rather than an array of boxed bytes.)
C# doesn't have checked exceptions
Java doesn't allow the creation of user-defined value types
Java doesn't have operator and conversion overloading
Java doesn't have iterator blocks for simple implemetation of iterators
Java doesn't have anything like LINQ
Partly due to not having delegates, Java doesn't have anything quite like anonymous methods and lambda expressions. Anonymous inner classes usually fill these roles, but clunkily.
Java doesn't have expression trees
C# doesn't have anonymous inner classes
C# doesn't have Java's inner classes at all, in fact - all nested classes in C# are like Java's static nested classes
Java doesn't have static classes (which don't have any instance constructors, and can't be used for variables, parameters etc)
Java doesn't have any equivalent to the C# 3.0 anonymous types
Java doesn't have implicitly typed local variables
Java doesn't have extension methods
Java doesn't have object and collection initializer expressions
The access modifiers are somewhat different - in Java there's (currently) no direct equivalent of an assembly, so no idea of "internal" visibility; in C# there's no equivalent to the "default" visibility in Java which takes account of namespace (and inheritance)
The order of initialization in Java and C# is subtly different (C# executes variable initializers before the chained call to the base type's constructor)
Java doesn't have properties as part of the language; they're a convention of get/set/is methods
Java doesn't have the equivalent of "unsafe" code
Interop is easier in C# (and .NET in general) than Java's JNI
Java and C# have somewhat different ideas of enums. Java's are much more object-oriented.
Java has no preprocessor directives (#define, #if etc in C#).
Java has no equivalent of C#'s ref and out for passing parameters by reference
Java has no equivalent of partial types
C# interfaces cannot declare fields
Java has no unsigned integer types
Java has no language support for a decimal type. (java.math.BigDecimal provides something like System.Decimal - with differences - but there's no language support)
Java has no equivalent of nullable value types
Boxing in Java uses predefined (but "normal") reference types with particular operations on them. Boxing in C# and .NET is a more transparent affair, with a reference type being created for boxing by the CLR for any value type.
This is not exhaustive, but it covers everything I can think of off-hand.
The following is a great in depth reference by Dare Obasanjo on the differences between C# and Java. I always find myself referring to this article when switching between the two.
http://www.25hoursaday.com/CsharpVsJava.html
C# has automatic properties which are incredibly convenient and they also help to keep your code cleaner, at least when you don't have custom logic in your getters and setters.
Features of C# Absent in Java
• C# includes more primitive types and the functionality to catch arithmetic exceptions.
• Includes a large number of notational conveniences over Java, many of which, such as operator overloading and user-defined casts, are already familiar to the large community of C++ programmers.
• Event handling is a "first class citizen"—it is part of the language itself.
• Allows the definition of "structs", which are similar to classes but may be allocated on the stack (unlike instances of classes in C# and Java).
• C# implements properties as part of the language syntax.
• C# allows switch statements to operate on strings.
• C# allows anonymous methods providing closure functionality.
• C# allows iterator that employs co-routines via a functional-style yield keyword.
• C# has support for output parameters, aiding in the return of multiple values, a feature shared by C++ and SQL.
• C# has the ability to alias namespaces.
• C# has "Explicit Member Implementation" which allows a class to specifically implement methods of an interface, separate from its own class methods. This allows it also to implement two different interfaces which happen to have a method of the same name. The methods of an interface do not need to be public; they can be made to be accessible only via that interface.
• C# provides integration with COM.
• Following the example of C and C++, C# allows call by reference for primitive and reference types.
Features of Java Absent in C#
• Java's strictfp keyword guarantees that the result of floating point operations remain the same across platforms.
• Java supports checked exceptions for better enforcement of error trapping and handling.
Another good resource is http://www.javacamp.org/javavscsharp/
This site enumerates many examples that ilustrate almost all the differences between these two programming languages.
About the Attributes, Java has Annotations, that work almost the same way.
Generics:
With Java generics, you don't actually get any of the execution efficiency that you get with .NET because when you compile a generic class in Java, the compiler takes away the type parameter and substitutes Object everywhere. For instance if you have a Foo<T> class the java compiler generates Byte Code as if it was Foo<Object>. This means casting and also boxing/unboxing will have to be done in the "background".
I've been playing with Java/C# for a while now and, in my opinion, the major difference at the language level are, as you pointed, delegates.
Please go through the link given below
msdn.microsoft.com/en-us/library/ms836794.aspx
It covers both the similarity and difference between C# and java

Categories