vote buttons
25 Feb 2015 by K Bonneau

Predict the output challenge (C#) - Part 3

Predict the Output Challenge - Part 1 (C#)
Predict the Output Challenge - Part 2 (C#)

Creating a Collection from List

What do you think the output of the following snippet is: 1,2,3,4,5 OR 1,2,3,4,5,6?

This is what MSDN says about the Collection constructor Collection<T>(IList<T>): Initializes a new instance of the Collection<T> class as a wrapper for the specified list. 

Its just a wrapper around your list object. Any changes you make to the list would get reflected in the collection and vice versa.

Is my type Nullable?

For Nullable<T> value type varaibles, the GetType() returns the type of T. Refer http://stackoverflow.com/questions/374651/how-to-check-if-an-object-is-nullable for more information on how to find out if a variable is Nullable.


What will get printed?

"I am B" is what will get printed. To give a simple one line reason, and not going into too much details about virtual table, the reason for this is that we are calling SaySomething on type of A, but it is overriden by B which is in the inheritance hierarchy and hence B's function will get called. Note that C does not override SaySomething, instead it redefines it and hence C's function will not get called.

If you have any interesting snippets to share, please do so in the comments below, or post a new article as the next part in this series.

Next: Predict the Output Challenge (C#) - Part 4