My Software Notes

Useful things I discover

Archive for the ‘Languages’ Category

Covariance and Contravariance. What do they mean again?

with one comment

I don’t have to deal with covariance and contravariance very often, so every time I do I forget which is which. So, just for my own benefit, here is a note describing them:

Covariance and contravariance are terms that refer to the ability to use a less derived or more derived type than originally specified.

Covariance – Enables you to use a more specific type than originally specified

E.g., in generics

We have a base type called “Feline” and we have a derived type called “HouseCat”.

IEnumerable<HouseCat> cats = new List<HouseCat>();
IEnumerable<Feline> gods = cats;
//Note: felines have a very high opinion of themselves :)

Contravariance – Enables you to use a less derived type than originally specified.

E.g., in generics

Using the same base and derived types as above.

IEnumerable<Feline> gods = new List<Feiline>();
IEnumerable<HouseCat> cats = gods;


Covariance and Contravariance (C# and Visual Basic)

Covariance and Contravariance in Generics



Written by gsdwriter

January 19, 2015 at 12:05 pm

Posted in .NET, Languages

To var or not to var. That is the question.

leave a comment »

You can always use or misuse or overuse Shakespeare to make a point.  Hopefully this is an example of “use” and not “misuse”.  🙂

Somewhere on this blog I posted about using “var” in C# (“var” is a pronoun).  In it I said you should only use it when it was obvious what the data type is.  Well, I’ve changed my mind.  What can I say?  Times change, people evolve, live with it.

I now use “var” all of the time.  I rarely, if ever, don’t use it.  If I am declaring a variable and setting it to null then I will explicitly name the data type, otherwise it’s “var”.

Why the change?  The first thing that led to it was some study of F#, which does implicit typing all the time.  Even if you don’t assign a value to a new variable the compiler will still figure out what the type is based on what you do with it later in your program.  Very nice.

(As an aside: Studying F# has made a big impression on how I code:  I tend to keep my variables immutable and declare another one if I am making a change – not 100% of the time as it would be impractical in my main languages (which, just now, are C#, TSQL and JavaScript), but probably 80 to 90%.  Another change caused by studying functional programming is that I am very aware of any side-effects my methods may cause and I try to write side-effect free methods and if they do cause side-effects I name them so it is clear that they do.  If you have only ever been exposed to OOP languages (like C#, Java, etc.) and procedural languages (like C, VB script, etc.)  I highly recommend studying a functional language.  It will expand your horizons.  In fact I recommend studying lots of different language types – more on that later.)

But back to the point.  So, studying a functional language that has implicit typing and seeing the advantages of that was the first reason.  The second reason was laziness.  The third and (for me) most important reason was that I really wasn’t gaining anything by explicitly naming the types.  Honest, in the years that I’ve been using “var” I have never had a problem figuring out a bug or how to modify some existing code because I used “var”.  So why would I not use it?  The fourth and final reason was that I can change the type of something and not need to change assignment statements. E.g., var myVar = SomeMethod(); If SomeMethod returns a bool and I change it to return a string – I don’t need to change that assignment statement.

If you need a deeper analysis of this then read Eric Lippert’s excellent article: Uses and misuses of implicit typing.  Or just start using “var” and see for yourself if it ever causes a problem.

Written by gsdwriter

April 21, 2011 at 8:46 am

JavaScript: I Repent

leave a comment »

I admit it – I have sinned.  I’ve been proud and arrogant.  

For years now I’ve had “JavaScript” listed on my resumé as one of the languages I know.  I listed it because, you know, JavaScript “isn’t really a language anyway” and I can “get by” with what I need to do with it because “nobody really develops with JavaScript” and anyway “JavaScript sucks”.  

Oh, the justifications for my arrogance.  It’s embarrassing now to look back and realize that I was daring to use a language that I knew virtually nothing about.

Well all that has changed.  I repent.  I have seen the light. (Praise dee Lord.  Hallelujah.  Etc., etc., etc.)

I will now admit the truth:  JavaScript is a real programming language.

And (until just a few days ago): I don’t really know how to program with it.

I think Douglas Crockford says it best in his brilliant book “JavaScript: The Good Parts“:

JavaScript is most despised because it isn’t some other language. If you are good in some other language and you have to program in an environment that only supports JavaScript, then you are forced to use JavaScript, and that is annoying. Most people in that situation don’t even bother to learn JavaScript first, and then they are surprised when JavaScript turns out to have significant differences from the some other language they would rather be using, and that those differences matter.

I just read that book from cover to cover and I can now honestly say for the first time that I actually understand JavaScript.  It IS a language and (when you use only the “good” parts) it’s quite an amazing language and (other than its syntax) it is NOTHING LIKE Java or C or C#.

How I program  JavaScript has changed dramatically – there is just no comparison to what I was doing before.

I’ve been regarding jQuery as the “solution” to JavaScript, but now I realize that jQuery is the solution to the DOM and that understanding JavaScript vastly improves my ability to use jQuery well.

If you haven’t read the book “JavaScript: The Good Parts” or watched the video series “Douglas Crockford JavaScript Master Class” then you don’t understand JavaScript well enough to use it correctly and you will be using it as if it is some other language and  making dumb mistakes (just like I did) that will be driving you crazy and making you curse JavaScript and wishing it would be cast into the pit along with whoever came up with it.  

So read the book and watch the videos and you too will see the light. Hallelujah!

Written by gsdwriter

December 19, 2010 at 12:04 pm

VB.NET Syntax for Object Initializers

leave a comment »

I don’t use VB.NET very much, so I keep forgetting the object initializer syntax.  So for my own benefit (and anyone else’s who has the same problem) here it is:

Dim acct = New Account() With { .Id = 10, .Name = "Joe Schmoe" }

Array initializer syntax is more like the C# syntax:

Dim intArray As Integer = { 1, 2, 3 }

And combining the two:

Dim acctArray() As Account = { _
                             New Account() With { .Id = 1, Name = "Mary Contrary" }, _
                             New Account() With { .Id = 2, Name="Fred Flintstone" } _

I won’t make any comments about how ugly VB.NET is because that would just start an argument and I’m a peace loving guy 🙂


MSDN: VB 9.0 Object and Array Initializers
Wriju’s Blog: VB.NET 9.0: Object and Array Initializers


Written by gsdwriter

July 31, 2010 at 3:36 pm

Posted in Languages

Programming Language Trends

leave a comment »

There is a fascinating web page called the TIOBE Programming Community Index.  The index lists programming languages and gives an estimate of their popularity based on various criteria.

The index is useful if you are wondering which languages are popular and which are most used, etc., but more interesting is to view the trends of usage by clicking on the language names in the ratings table.

For example, as of right now (Oct 2009) Java is the top language, so if you were a new programmer you might be tempted to learn Java because it’s the most popular and there is probably lots of demand for Java programmers. But before you rush over to Amazon and buy Head First Java or Learning Java, click on the link to the long term popularity trend of Java and you might have second thoughts:  Java’s popularity is on the wane.  It’s popularity graph from 2001 to now, goes down at a 30 degree angle.

From its peak in 2001 in the #1 position with a rating of 26.5%, Java crashed to second place and a rating of 14.8% in 2004.  It recovered a bit by the end of 2005, but has continued to fall ever since.  If the trend continues then it won’t be #1 much longer.

In contrast, the long term popularity trend of C# is quite the opposite.  It’s graph is going up at almost a 45 degree angle.  So the neophyte programmer may be tempted to buy Learning C# 3.0 or C# in Depth: What you need to master C# 2 and 3.

Other languages that have very promising long term uptrends are Python and JavaScript.

Languages that were on uptrends but have now flattened out are PHP and Ruby – although they are still uptrending, just not as much as C#, Python and JavaScript.

Languages that are going down are Java, C (although it has made a small recovery since 2008), C++,  and Perl.

It all makes fascinating reading, so head on over and take a look.

Written by gsdwriter

October 18, 2009 at 1:00 pm

Posted in Languages

Tagged with ,

Adding that “all” element to a combo box

leave a comment »

In the past when data binding a combo box, I’ve found that adding the “(all)” or “(none)” element to the top of the list has always seems unaesthetic to me.  A funny choice of words, you may think, but to me well written code is aesthetic and adding that top element just seemed messy. 

If you were using a data set then you had to create a row and stick it in the table in the data set and then sort the thing so your element would come to the top and then bind to the table or to the data view.

If you weren’t data binding but were loading elements in a loop, you still had to stick that “all” element in there to make sure it got on top.

Binding to a collection of objects was a bit cleaner but I still didn’t much care for it.

But now we have LINQ and at last I’ve found the aesthetic way to do it!

using (var db = new ProductDataContext())
    var results = from p in db.ProductTypes
                  orderby p.Description
                  select p;
//Add an "All" item to the top of the list
var all = new ProductType()
    ProductTypeCode = PRODUCT_TYPE_CODE_ALL,
    Description = PRODUCT_TYPE_DESCR_ALL
prodTypeCollection.Insert(0, all);

I like LINQ.  It is making my job a hell-uva-lot easier and more enjoyable.

Written by gsdwriter

June 7, 2009 at 8:56 pm

Posted in Languages, LINQ

Tagged with , ,

Fun with lambda expressions

with one comment

While creating C# 3.0 equivalents to the Martin Fowler example Closures in Ruby in my last post (Closures in C# (better known as lambdas)), I was having so much fun that I carried on and came up with this:

Here are the “inline” versions (the PaidMore example is my favorite – just look at the original C# 2.0 version and you’ll see how far we have come):

Example Inline C# 3.0
var managers = emps.FindAll(e => e.IsManager);
var managers = emps.Where(e => e.IsManager);
var highPaidEmps = emps.FindAll(e => e.Salary > threshold);
var highPaidEmps = emps.Where(e => e.Salary > threshold);
Func<int, Predicate<Employee>> PaidMore = amount => e => e.Salary > amount;
Using PaidMore
var highPaid = PaidMore(150);

var areHighPaid = emps.FindAll(highPaid);
var areHighPaid = emps.Where(e => highPaid(e));

(Note that “Where()” returns an anonymous type so if you wanted a List<Employee> you’d need to call the “ToList()” method.)

I also did LINQ expression versions of all the above, and whilst they are implementing lambdas in the background, you can’t see them in the code, so I didn’t include them here.

Getting a little off the subject of closures, another cool use of the C# 3.0 features is to implement PaidMore as an extension method:

public static bool PaidMore(this Employee e, int amount)
    return e.Salary > amount;

Then call it like this:

var areHighPaid = emps.Where(e => e.PaidMore(150));


var areHighPaid = from e in emps
		where e.PaidMore(150)
		select e;

Closures/Lambdas not only open up a lot of possibilities but also add a new element of fun to C# programming.

Written by gsdwriter

June 7, 2009 at 3:06 pm

Posted in Languages

Tagged with , ,