An explanation of implicit and explicit conversion in C#

Given a method signature that expects two nullable DateTime parameters… protected int CalculateActualDuration(DateTime? startDate, DateTime? endDate) … SamIAm asked on Stack Overflow about how the compiler understands nullable types: I am able to call the method by passing in both a DateTime? and a DateTime. So how does the compiler

Read More

The effect of the Obsolete attribute on a class is ignored when there's an interface involved

While marking some code obsolete the other day, I noticed an unexpected behavior (at first glance). Say you have a class, and an interface it implements. The second argument (true) indicates whether or not you’re allowed to call the method, and it means the difference between a simple warning

Read More

An extension method for passing a column name to SqlDataReader.GetFieldValue in C#

I was reading some or another question on Stack Overflow today, and someone happened to reference the SqlDataReader.GetFieldValue method. It’s a generic method that returns the value of a column, given its 0-based ordinal value. using (var conn = new SqlConnection("yourConnectionString")) { using (var cmd = new SqlCommand("SELECT name,

Read More

Chaining Assignment Operations (or, using a statement as the expression in another statement)

Background I setup the following property in a WinForms Form, to get an EventAggregator instance from Unity. (This is tightly-coupled legacy code that doesn’t currently support dependency injection via ctor.) private IEventAggregator eventAgg; private IEventAggregator EventAgg { get { if (eventAgg == null) eventAgg = UnityInstanceProvider.GetInstance<IEventAggregator>(); return eventAgg; } } The

Read More

Under the Hood - Ternary Operator [ ?: ]

Someone posted the following question on Stack Overflow today: (since deleted) Is there a better way according to best practices to do this type of ternary operation without breaking it down into an if block? visitorInfo = string.IsNullOrEmpty(visitorInfo.latitude) ? DetermineGeolocation(visitorInfo) : visitorInfo; Meaning, without breaking it into a complete

Read More