As part of DotNetDoc's new "Ask the Doc" format, we are starting our journey by taking a page from the Zen Master himself Scott Hanselman. We will be walking through his list of questions posted in his, "What Great .NET Developers Ought To Know" post. We will not only try to answer the questions but give each a "deep dive" so that we not only can answer the question, but so that we UNDERSTAND the answer. We will go one question at a time until we reach the end. I hope you enjoy, and thanks Scott for the thought provoking questions.
.Net Ought To Know #5 : What is strong-typing versus weak-typing? Which is preferred? Why?
In strongly-typed programming languages you usually have to declare variables prior to using them. Strong-typing is the strict enforcement of [type] rules. All types (int, short, long, string) are know at compile time and are statically bound. So C# is a strongly-typed language because variables must be assigned a type before you use them. If you came from the ASP world then you will remember having to use either Javascript or VBScript. Variables that you declare in either of those languages can hold any data type which makes it weakly-typed.
But lets take this up a level. Instead to talking about programming languages, lets talk about strongly-typed/weakly-typed objects. The DataSet object is a great example. If we use a weakly-typed dataset, the developer needs to know the name of the table and the name of the field being requested. Since we are just passing strings, this code will compile and will not show any possible problems (like typing the name of the table wrong) until run time.
string s = (string) myDataSet.Tables["Customers"].Rows[0]["CustomerID"];
If our Dataset is Strongly-Typed, we are able to access the names of the tables and columns directly. Any errors are caught at compile time.
string s = myDataSet.Customers[0].CustomerID;
I am not really going to argue which is better, I will leave that up to you. I will leave you with this question though; would you rather catch your errors at compile time, or run-time?
Happy Programming.
Doc