December 21, 2017

What makes C# great?

By Angus Kinsey

C# is everywhere these days. Whether you're writing a web application or a native piece of software, you can find a way to incorporate the Microsoft stack. When I heard that Matt Groves was putting together the first C# Advent Calendar, I knew that the team at Centare needed to be a part of it! Many of our developers have been using C# for a large portion of their careers. I was curious what some of these seasoned technologists favorite C# features were. Here's what they said:


Adam Pritzl - Developer
Adam Pritzl
Developer

Dates & Times Are Easy...Right?

JavaScript has made a huge emergence, and nearly every application I've worked on in the past five years has used one framework or another to create UIs that need to interface with the back-end. Date and time serialization and conversions have led to countless headaches. Different standards, formats, and time zones are all sources of problems.

The Scenario

The scenario I'd like to focus on is a simple one, but could bite you if you don't think through all the edge cases. Let's say you're writing an application that is for scheduling appointments using a web browser.

The user will enter a date using a date picker or text field. Whatever the case, you always need to know that the time zone of the user might be different from the server, and the time zone of the place you are making the appointment might be different from the server. That's three different time zones! If we only had a way to manage this. It's a good thing C# and .NET have many tools for dealing with this.

So, the user has submitted their appointment to the server. Simple, right? Not so much. The user was visiting their in-laws in Delaware, and forgot to schedule their appointment in Wisconsin, while the server hosting the application is on the west coast.

The user is going to want to pick the appointment for the time zone in which the office they'd like to make the appointment is in. So, the user picks a date and time and clicks submit. But in what time zone was that for?

Since we know that the user is choosing their appointment date/time for a specific time zone, we can create the date with that time zone offset. Then we're going to want to convert to ISO 8601 using .toJSON(). This will give us our zero offset UTC date/time we are looking for. That's going to look like this.

2017-12-18T00:48:00.000Z

If we don't convert this date to UTC the server will serialize the date to be in the time zone of the server.

Since we know that the client is communicating the datetime to the server in UTC we can take the date and use the .SpecifyKind() method to make sure that the system knows that this is a UTC date time. This is important because it influences how the date is serialized. For example, imagine if this application was moved to a different time zone for disaster recovery. If we didn't set this property then we might have issues with times being converted differently when saving the appointment. It also will influence how methods like .ToLocalTime(), .ToUniversalTime(), and .ConvertTimeFromUtc() behave as well.

public class Appointment
{
    public DateTime AppointmentStartTime { get; set; }  
}

public void Post(Appointment appointment)
{
    var utcDate = 
        DateTime.SpecifyKind(
            appointment.AppointmentStartTime,
            DateTimeKind.Utc);
    // Save appointment to database w/ UTC time
}

Now the appointment date is approaching and we need to send the user an email reminder about their appointment. Since the appointment has been made, that application has moved to a different time zone. Because we took care and stored the appointment time in UTC and set Kind property to UTC, we can confidently convert the time from UTC to the time zone that the office is in.

TimeZoneInfo cstZone = 
    TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
DateTime cstTime = 
    TimeZoneInfo.ConvertTimeFromUtc(timeUtc, cstZone);

Conclusion

Dates are not easy. The scenario we just reviewed is a common one and could contain many different bugs if you're not careful.

References


Goutham Pai - Developer
Goutham Pai
Developer

C# 6 String Interpolation

On any project of significant size, the maintainability and readability of the code is essential. C# has several features that enable a developer to write easily read code.Today, I would like to talk about my favorite feature that lets people do this - C# 6 string interpolation.

How do I use it?

String interpolation is a feature that lets the developer construct strings with both static and variable values in a more readable fashion than with basic string concatenation or through the use of String.Format The string interpolation syntax is shown in a simple example below.

var numberOfApples = 6;
var myName = "Goutham";
// Will print out
// Goutham has 6 apples.
var interpolated = $"{myName} has {numberOfApples} apples.";

While that is a relatively basic example, more can be done with it in terms of formatting. For example, you can specify the date format of a datetime within the string.

var currentTime = DateTime.Now;
var interpolated = $"{currentTime.Date:M-dd-yyyy}";

Where could I use it?

The applications for a more readable string are numerous. Some common uses are in having detailed, readable logging and error messages. I hope this helps everyone write more readable code. For more info on string interpolation, check out the Microsoft reference documentation on it.


David Pine - Developer
David Pine
Developer

The Future of C#

I'm excited to share my love of the C# language. The C# language team has been actively innovating and working with the community to evolve the language with new features and improvements. Shortly after C# 7.0 shipped, the team decided that point releases was the way to go - since then we've been blessed with C# 7.1 and 7.2. The future of C# is bright indeed!

I wanted to take a moment to share what is currently being planned for C# 8, the next major release of C#. Since becoming open-source the process for which new features are introduced into the language are more transparent. There are several phases for which new features are discussed, adopted and then specified.

C# is designed by the C# Language Design Team (LDT) in close coordination with the Roslyn project, which implements the language.

Typically when a "proposed" feature is discussed enough, and it decided to be considered - it will move into the "prototype" phase. The prototypes are very useful to sandbox the proposed feature, and test it out. It allows for a preemptive trial if you will of the feature.

C# 8 Features

Of all the proposed features sitting out there, the following list are the features that have the most attention and several have working prototypes.

  • Nullable reference types
  • Async Streams
  • Default Interface Implementations
  • Extension Everything
There is a great video of Mads Torgensen demonstrating and white-boarding these features with Seth Juarez.

We're going to take a look at the "null reference types" prototype in action. Luckily, Bill Wagner was kind enough to point me to the setup instructions to access the preview feature.

Nullable Reference Types

When I first heard about this, I thought it was an oxymoron. Clearly Mads has gone...well, MAD?! Of course we know that reference types are nullable, that is in their nature. Thanks to their inventor Tony Hoare, who has been quoted countless times calling his invention the "billion-dollar mistake". If you're familiar with C# already, you are familiar with the introduction of Nullable<T> that servered as a means for allowing struct (value-types) to be null. The syntax is the same in the proposal. Any reference type that you want to indicate as nullable you can simply suffix the type declaration with a ?. Let's consider the following:

public class Person
{
   public Guid Id { get; }
   public int Age { get; }
   public (string first, string last) Name { get; set; }
}

We have a simple class, a reference-type object that will represent a person. Now imagine that we have a repository that exposes a means of requesting an individual person by an identifier. We can express to the consumer that the person returned might be null.

public interface IRepository<Person>
{
    Task<Person?> GetByIdAsync(Guid id);
}

Note, that this is identical in terms of functionailty as a non-nullable reference type. Again, we are just expressing intent. Now Roslyn has the opportunity to chime in and act on this intent. Consider the following:

var person = await _personRepositroy.GetByIdAsync(id);
var age = person.Age;
var (first, last) = person.Name;

In this example, the .NET compiler will provide a warning that states there is a possibility for a NullReferenceException - as we are attempting to access members on an instance that explicitly expresses its intent to be potentially null. The warning comes with a suggestion to perform a null check.

var person = await _personRepositroy.GetByIdAsync(id);
if (person != null)
{
    var age = person.Age;
    var (first, last) = person.Name;
    // Use safely...
}

Conclusion

The C# language is evolving more and more at a staggering rate. If you take a look at the history of C#, it is easy to see the trend. I am thankful that I get to program in this langauge, and I hope that you are too.


What is your favorite C# feature?


About Angus Kinsey

Angus is a passionate problem solver who thrives in collaborative and creative environments that allow his analytical style to shine. He prides himself on his ability to analyze problems in order to ask the right questions and ultimately produce efficient and effective solutions.