Brendan Enrick

Daily Software Development

What’s New in C# 7- My Course on DevIQ

Yesterday, I was working with my dev team, and some people came across some C# 7 code. Specifically, they were seeing some code using Pattern Matching, and weren’t sure about it. Not everyone was familiar with C# 7, a failing on my part. If you’re also not familiar with all of the new features in C# 7, I’d recommend checking out my What’s New in C# 7 course on DevIQ. In the course, I go through all of the new features of C# 7, explaining both how they work and when to use them.

I talk regularly at conferences about C#, and have given talks on C# 6, C# 7, and the combination of the two. When I ask people if they’re using a version of C#, most people acknowledge they are, but when I ask about specific features, most hands drop. I find that many developers are not using the features made available to them until long after it’s available to them. Don’t miss out on these!

As C# grows it’s important to stay up-to-date on everything that it offers you! Check out my course today and get your quick-start to using the new features in C# 7!

What You Will Learn About C# 7

In this course, you will learn:

  • Output Variables
  • Pattern Matching
  • Local Functions
  • Improved Literals
  • More Expression Bodies
  • Throw Expressions
  • Tuples
  • Ref Returns


NewInCSharp7

What’s New in C# Bundle

And many developers need to know about C# 6 still. I did a course covering C# 6 as well, so you can check out the bundle I set up. The What’s New in C# Bundle includes both What’s New in C# 6 and What’s New in C# 7! Allowing you to learn everything you need to know to bring your C# project up-to-date!

NewInCSharpBundleThumb

What’s New in C# 6 - My Course on DevIQ

If you’re looking to improve your C# 6 code by taking advantage of the new features added into the language, I’ve got you covered. By using C# 6, you’ll be able to clean up your code, and make things more concise. This was one of the focuses in the design of C# 6. You can clean up and remove the clutter from your projects by taking advantage of C# 6. My C# 6 course on DevIQ will show you how to use these new features to improve the code you’re writing today. You already have the tools and capability, and now you can learn how to take advantage of it!

As a consultant, I’ve worked with developers in different companies, and I find that most organizations are barely using the features of C# 5 let alone using C# 6. When I talk at conferences, most people say they’re using C# 6, and they technically are using it. Their code is compiled using C# 6, but they’re not using all of the features or know how powerful they can be!

To help teams with this, I created a quick-start, What’s New in C# 6 course on DevIQ that will help you get started using C# 6!

What You Will Learn

In the course, you will learn about:

  • Property and Method Improvements
  • String Improvements
  • In-Line Code Improvements
  • Exception Improvements

 

Whats New In C# 6

Try Writing Try Methods

When I say "Try Methods", I am of course referring to the common prefix "Try" on a method, which implies that the method is going to attempt to do what you're asking by using an output parameter for the operation and using the return value to indicate whether the attempt succeeded.

The common ones that people see in the .NET Framework are the TryParse methods, which attempt to parse something and if it can't be parse, they assign the default value to the output parameter and return false. If the succeed, the parsed value will be placed in the output parameter and the return value will be true. If the code failed, the convention is to use the type’s default value to assign to the output parameter. This lets you write code like this:

int someNumber;
int.TryParse(userInput, out someNumber);
// use the number entered or the default 0
int result = 1 + someNumber;

 

This is also great when you're going to be checking whether the method succeeded. In fact, you can use the try method directly in the if block, which usually makes things nice and clean. Here is an example of using them like that:

int someNumber;
if (int.TryParse(userInput, out someNumber))
{
    // Do something with someNumber
}
else
{
    // Invalid input: handle this case accordingly
}

 

Yes, you know all of this and have seen it before, however, are you writing these types of methods yourself or is your only experience with them the standard TryParse ones?

What I am trying to emphasize here is that you need to write your own Try methods in your code. You will thank yourself later.

Everyone can see the obvious benefit of not having to check for the default value to see if it the method worked. You also don't have to have ugly Try-Catch logic in your code. You get an if statement instead.

The real benefit of a writing a Try method has nothing to do with what I've already said. The most important benefit, in my opinion, is that you have a return value from it that isn't the value you are using for your logic. By having this return value for its success, you have to decide on how to handle the case where it failed.

There are important cases that might be forgotten, but having a return value means that I need to handle the return value. When I have it, I need to decide what to do with it. There may be a message I need to display to a user. There may be logging I need to do. I might be able to ignore that case. What is important, however, is that I thought about how to handle it. I had the chance to make sure that I handled the case correctly.

Create your own “Try” methods. I recommend looking into creating your own “TryParse”, “TryGet”, TryDelete”, and anything else that has a chance of failure that you may want to handle.

Fun with IL DASM and Duck Typing

So as a bit of fun, since I just wrote a post about duck typing and foreach loops, I thought I would take a look at what’s happening under the hood when we use this trick. To start with, I will have two classes, which each have GetEnumerator methods. The first one is using DuckTyping, so it doesn’t implement any interfaces. The second one is implementing the IEnumerable interface. Finally, I have a third class with a method that just uses a foreach loop over instances of the other two classes.

The code for my little example looks like this:

public class DuckCollection
{
public IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
}

public class EnumerableCollection : IEnumerable
{
public IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
}

public class ForEacher
{
public void DoForEach()
{
var duckCollection = new DuckCollection();
foreach (var thing1 in duckCollection)
{

}

var enumerableCollection = new EnumerableCollection();
foreach (var thing2 in enumerableCollection)
{

}
}
}

After I compile this code, I’ve opened it up with IL DASM, so I can see what the generated IL is for this code.
.method public hidebysig instance void  DoForEach() cil managed
{
// Code size 146 (0x92)
.maxstack 2
.locals init ([0] class DuckTypingILCode.DuckCollection duckCollection,
[1] object thing1,
[2] class DuckTypingILCode.EnumerableCollection enumerableCollection,
[3] object thing2,
[4] class [mscorlib]System.Collections.IEnumerator CS$5$0000,
[5] bool CS$4$0001,
[6] class [mscorlib]System.IDisposable CS$0$0002)
IL_0000: nop
IL_0001: newobj instance void DuckTypingILCode.DuckCollection::.ctor()
IL_0006: stloc.0
IL_0007: nop
IL_0008: ldloc.0
IL_0009: callvirt instance class [mscorlib]System.Collections.IEnumerator DuckTypingILCode.DuckCollection::GetEnumerator()
IL_000e: stloc.s CS$5$0000
.try
{
IL_0010: br.s IL_001c
IL_0012: ldloc.s CS$5$0000
IL_0014: callvirt instance object [mscorlib]System.Collections.IEnumerator::get_Current()
IL_0019: stloc.1
IL_001a: nop
IL_001b: nop
IL_001c: ldloc.s CS$5$0000
IL_001e: callvirt instance bool [mscorlib]System.Collections.IEnumerator::MoveNext()
IL_0023: stloc.s CS$4$0001
IL_0025: ldloc.s CS$4$0001
IL_0027: brtrue.s IL_0012
IL_0029: leave.s IL_0048
} // end .try
finally
{
IL_002b: ldloc.s CS$5$0000
IL_002d: isinst [mscorlib]System.IDisposable
IL_0032: stloc.s CS$0$0002
IL_0034: ldloc.s CS$0$0002
IL_0036: ldnull
IL_0037: ceq
IL_0039: stloc.s CS$4$0001
IL_003b: ldloc.s CS$4$0001
IL_003d: brtrue.s IL_0047
IL_003f: ldloc.s CS$0$0002
IL_0041: callvirt instance void [mscorlib]System.IDisposable::Dispose()
IL_0046: nop
IL_0047: endfinally
} // end handler
IL_0048: nop
IL_0049: newobj instance void DuckTypingILCode.EnumerableCollection::.ctor()
IL_004e: stloc.2
IL_004f: nop
IL_0050: ldloc.2
IL_0051: callvirt instance class [mscorlib]System.Collections.IEnumerator DuckTypingILCode.EnumerableCollection::GetEnumerator()
IL_0056: stloc.s CS$5$0000
.try
{
IL_0058: br.s IL_0064
IL_005a: ldloc.s CS$5$0000
IL_005c: callvirt instance object [mscorlib]System.Collections.IEnumerator::get_Current()
IL_0061: stloc.3
IL_0062: nop
IL_0063: nop
IL_0064: ldloc.s CS$5$0000
IL_0066: callvirt instance bool [mscorlib]System.Collections.IEnumerator::MoveNext()
IL_006b: stloc.s CS$4$0001
IL_006d: ldloc.s CS$4$0001
IL_006f: brtrue.s IL_005a
IL_0071: leave.s IL_0090
} // end .try
finally
{
IL_0073: ldloc.s CS$5$0000
IL_0075: isinst [mscorlib]System.IDisposable
IL_007a: stloc.s CS$0$0002
IL_007c: ldloc.s CS$0$0002
IL_007e: ldnull
IL_007f: ceq
IL_0081: stloc.s CS$4$0001
IL_0083: ldloc.s CS$4$0001
IL_0085: brtrue.s IL_008f
IL_0087: ldloc.s CS$0$0002
IL_0089: callvirt instance void [mscorlib]System.IDisposable::Dispose()
IL_008e: nop
IL_008f: endfinally
} // end handler
IL_0090: nop
IL_0091: ret
} // end of method ForEacher::DoForEach


 

Yes, it’s a bit ugly, but you will notice that other than naming, the code is just repeated twice. This is of course what we would expect, since the code should treat it the same regardless. All the foreach loop needed was to be able to get the object from the GetEnumerator method. Once it has that, it just uses the enumerator to do all of the work. This means that either class should work just as well.

This is the repeated line of code that shows up in two places to get the enumerator it will be using for its MoveNext() and GetCurrent() methods.

IL_0009:  callvirt   instance class [mscorlib]System.Collections.IEnumerator DuckTypingILCode.DuckCollection::GetEnumerator()
IL_0051: callvirt instance class [mscorlib]System.Collections.IEnumerator DuckTypingILCode.EnumerableCollection::GetEnumerator()

 

Now if you’re really paying attention, you will have looked at the Try-Finally block that is in the code to handle our IDisposables. That’s another neat thing happening behind the scenes, but that’s another blog post entirely.

If you would like to see another cool thing in the .NET Framework, you should check out what else you can do with Null Instance methods if you change those callvirts.

Foreach, IEnumerable, IEnumerator, and Duck Typing

During my Software Craftsmanship Precompiler session, I heard one of the students say, “all you need is an IEnumerable to use a foreach loop”. This sparked a bit of fun when I asked Steve Smith, my co-presenter, if that was correct. He confirmed that it was, and I disagreed. Being the scientists that we are, we decided to try it and see what happened. I of course knew that duck typing in C# should allow the Foreach loop to compile without anything having the method required by the IEnumerable interface. This means that we just need a GetEnumerator method.

We wrote the code that did this and it compiled!

Duck typing is awesome, because it allows the language to treat my type the way I want it to because it has the right tools to do the job. The term duck typing comes from the idea that if it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck.

In the foreach loop example, duck typing assumes that what you have here is able to be enumerated, because it has a method to get the enumerator. If we look at the IEnumerable interface, we can see that this is what we are required to implement.

public class MyCollection : IEnumerable
{
public IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
}

Now that we have our collection written and implementing IEnumerable, we can write a foreach loop that uses our collection.

var myCollection = new MyCollection();
foreach (var thing in myCollection)
{
// Do something with the thing
}

Finally, because of the duck typing in C#, we can remove the interface from the code, but keep the method.

public class MyCollection
{
public IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
}

It still compiles!

One of the many cool things about C# that I love. It’s a fun language, so go experimenting!

Commenting Methods Using Liskov Substitution Principle

After reading the title of this post, some people might be wondering why I am advocating commenting at all, because I’ve spoken out against commenting code before. My team and I were recently reading through some code that was littered with comments, and I do mean littered. There were tons, they were mostly useless statements like “//run”, and I swear there were more of them than actual code. This of course sparked some preaching to our choir about how comments in code are often less-than-useful. We of course settled on the time when they are useful being the XML comments on methods, but those should also only be used when writing public libraries where others will not have access to the source code or unit tests.

Comments on those methods are useful since tons of people will use the method and will not be able to see the guts of the method or examples of how to use it. This makes the comments useful. However, they need to be kept up-to-date (difficult task).

So what does all of this have to do with Listkov Substitution? Well, the principle basically says that all of the classes which implement an interface (or inherit) need to work the same way. There should be no difference between implementations as far as the calling code is concerned. In fact it is really about making sure that we maintain a consistent abstraction. If we say something about the interface it must hold true for the implementation. This means that any comments about the interface must hold true for every implementation.

We were wondering if the comments needed to be on each of the concrete classes or if we could just put it on the interface, and this was confirmed for me by Ben Heimann who quickly made an interface and a concrete class. Then he commented just the interface method and not the concrete one. We of course knew we would see the comment when using the interface, but we also saw it when we were dealing with the concrete class. Great work Visual Studio 2010! This means we don’t have to duplicate and also signals that we should follow LSP.

The concern is that if you have the comment in both places you would have to update them both. This also means that they could differ, and if they ever needed to intentionally differ then it means that we are violating LSP. Having the comment in the one place should at least point to the fact that we should maintain the same behavior for the calling code in all implementations of our interfaces.

Using Dynamic Typing When an Interface was Needed

Interfaces and base classes allow us a great deal of power in object oriented programming. We are able to accept a base type or interface and be given an implementation or an inheritor and continue working correctly. What if, however, we need to be able to accept more than one type, which have the same methods or properties, but to not share an interface or base class? Often the best answer is to add a common interface to these, so that the shared behavior is defined. In most of my cases when I need to do something like this, it is because I don’t have the source code for one or more of the classes.

Our answer in this case is the dynamic types which we added in to C# 4.0. In this new revision of the language, we are able to declare an object deferring its type until runtime. We will define how we will use the object now, and at runtime our code will attempt to use that object.

The following is some example code showing how to use the dynamic keyword to use two classes interchangeably:

class Program
{
public static List<DateTime>
Dates = new List<DateTime>();

static void Main(string[] args)
{
var someClass = new SomeClass(DateTime.Now);
GetEventDate(someClass);
var otherClass = new OtherClass(DateTime.Now);
GetEventDate(otherClass);

var values = Dates.Select(d => d.ToShortDateString());
Console.WriteLine(string.Join("---", values));
}

private static void GetEventDate(dynamic objectWithDate)
{
Dates.Add(objectWithDate.Date);
}
}

public class SomeClass
{
public DateTime Date { get; set; }

public SomeClass(DateTime date)
{
Date = date;
}
}

public class OtherClass
{
public DateTime Date { get; set; }

public OtherClass(DateTime date)
{
Date = date;
}
}

So in this example, if we say that I didn’t have access to OtherClass in order to give it some interface, using the dynamic would allow me to get around this and use a convention-based approach to development. When the alternative is some cluttered approach, I am always in favor of simplifying the readability and usability of my source code. Now there is less of a reason to complain that a certain class from a library or generated code doesn’t implement an interface. (There is still reason, but at least we can avoid some of the issues at play.)

A Quick Answer About Reference Types

Reference types were created to make dealing with pointers a little bit easier. They hide away the details of the pointers, so that the programmer need not think about them. In many ways I think they’re awesome, because they really achieve that goal. The problem is that by abstracting away the details of the pointers they’re sometimes difficult to work with, because they can be a little bit confusing.

I received a comment about this topic on one of my ASP Alliance articles explaining value types and reference types in C#.

First of all the article is excellent.
But why the following program produces output as:: abc:xyz
it should produce xyz:xyz.
I am confused...Plz help
The Code:
string myName = "abc";
string authorName = null;
authorName = myName;
authorName = "xyz";
Console.WriteLine("{0}:{1}",myName,authorName);
Console.ReadLine();
The Actual Output:
abc:xyz
The Expected Output:
xyz:xyz
as it's areference type only one copy is shared between references.

How about if we take this step by step looking at the variables and their values, and I’ll be able to explain why the behavior is as you’ve found. First here is the code we’ll be looking at.

string myName = "Brendan";
string authorName = null;
authorName = myName;
authorName = "Enrick";
Console.WriteLine("{0}:{1}",myName,authorName);
Console.ReadLine();

We are expecting it to print out “Brendan:Enrick”.

Red is for the variables and orange is for referenced values for those variables.

ReferenceTypes1

Notice that when we set a variable equal to a literal string value we get a new location in memory, but when we set it equal to another variable all we are doing is copying the pointer to that memory location. However, when we then set that variable equal to a new literal value it doesn’t replace the old one for both since they each had a pointer. It just creates a new location in memory with that value and assigns a pointer to that variable.

The type of behavior that the writer of this code was trying to achieve could be handled by pointers very easily, but reference types take away control of pointers. Loss of freedom for the sake of safety one might say. Now that I’ve said that everyone will switch back to using c++ to get their pointers back.

Thank you for asking the questions saurabh. I hope this thoroughly answers your question. If you have any more, please feel free to ask them as well.

Working with Interfaces - Practical Uses

Expanding on an article I wrote a couple of years ago where I explained interfaces in C#, I’d like to explain why people should use interfaces. I received an email from a reader of my ASP Alliance article. He understands how interfaces work, but he’s trying to see why so many people are raving wildly about their greatness. His questioning of them is great, because it really is not obvious why interfaces are useful. Anyone who says otherwise is just trying to brag.

A couple of years ago, you wrote an article for ASP Alliance called "Understanding Interfaces." Once again, I saw how the code works, once again, I failed to see how it will benefit me.

Here's where everything breaks down for me: You create an interface with just method, property and event signatures. Then you inherit them in a class, recreate these same signatures and write the code to implement these methods and properties.

So I’ll start by mentioning that nearly all patterns, practices, principles, etc. in software development are based on code reuse. One of the most important reasons for code reuse is change. Developers are always responding to and creating changes. We must mitigate the risks of change, identify where changes will occur, and we must make changes.

Right about now you might be thinking, “but interfaces don’t reuse code. They just force you to implement new code. Using inheritance would be the way to achieve code reuse.” You ate technically correct. You understand how interfaces work, but you’re not seeing why we use interfaces. Interfaces themselves do not give us code reuse at all, however, they enable us to achieve code reuse.

Remember that I said that we must identify where changes will occur. Making this identification allows us to isolate changes thus mitigating the risks of changes and allowing us to make changes. Isolating the places that change also allow us the reuse the code which does not change, so by keeping some parts separate we can reuse others. The interfaces are for the places we can’t reuse the code.

Interfaces are “places of change”. Each implementation of the interface is a variation on how that required piece of the puzzle could have been implemented. This is contrary to how you’ll see a lot of interfaces used. It is sometimes difficult to see this as the behavior of interfaces, because people overuse interfaces.

As I see it, I could have saved a whole lot of time by not creating the interface in the first place! I mean, it's not doing any work. I still have to create the signatures in the class. Why on Earth do people praise these things and call them the answer to multiple inheritence? They don't do anything!

It is mostly true that interfaces don’t do anything. As far as being executable code is concerned an interface is basically just a worthless extra step, so why would we use them? Declaring an interface is like saying, “there is more than one way that this behavior could be implemented, but interactions with this behavior should be done this way only.” Having that common “interface” allows us to use any of these implementations interchangeably.

When to Use Interfaces

Some people would recommend that interfaces should be used everywhere. I’ve heard people say that no variable should be declared with a concrete type if it can be avoided. That may be a valid point, but if you’re just learning how interfaces can be useful that is a bad approach. If you don’t see value in interfaces, you will certainly not see the value of them when people use them everywhere. This washes them out and obfuscates their purpose.

Interfaces are used for logic which will have multiple or changing implementations. This means that we should use them in places where we will out of necessity have duplicate logic. Using the interface is what allows us to do this. Take a look at this code for composing a letter.

public string ComposeLetter(string recipientName, 
string messageBody, bool isFormal)
{
string messageText = string.Empty;
if (isFormal)
{
messageText += GetFormalGreeting(recipientName);
}
else
{
messageText += GetCasualGreeting(recipientName);
}

messageText += messageBody;

if (isFormal)
{
messageText += GetFormalSignature();
}
else
{
messageText += GetCasualSignature();
}

return messageText;
}

Notice how we have these flow control operators dictating how the code will execute. What will happen if we need to have a third option for greetings and signatures for family members? We might add another else-if or we might use a switch. Either way this code gets larger and changed every time.

However, if we identify the aspects of the code that are changing we can isolate them and mitigate the risks of changing the code by keeping separate the logic which has multiple implementations. Notice we have already used one form of encapsulation by keeping each of those pieces of logic in separate methods. The logic we haven’t encapsulated is the flow control.

We can create an interface for it. The best name I’ve got for now is IFormalityGenerator, which is not a great name, but it will do for now. I’ll create that interface with two methods: GetGreeting and GetSignature. Very simple interface. Now we can rewrite our method to look like this.

public string ComposeLetter(string recipientName, string messageBody, 
IFormalityGenerator formalityGenerator)
{
string messageText = string.Empty;

messageText += formalityGenerator.GetGreeting(recipientName);

messageText += GetMessageBody();

messageText += formalityGenerator.GetSignature();

return messageText;
}

We now just make the decision sooner and only once which implementation we are using. If this is a formal letter we will use the FormalFormalityGenerator. If it is casual we will use the CasualFormalityGenerator. Down the road when we create one for family members we can just go and create an implementation for the FamilyFormalityGenerator. We’ve made it so we create new code each time instead of going and changing the existing code in this method.

The power of an interface is in its ability to encapsulate the volatile aspects of a program and isolate that which can be reused more easily.

Implementing IEnumerable and IEnumerator

Working with a foreach loop is the primary reason to implement the IEnumerable and IEnumerator interfaces. You’ll want one of each of these to work with the loop.

I am going to do an example DateRange class which will implement IEnumerable<DateTime> and will allow us to iterate through a non-existent collection of DateTime objects.

Note: I am aware of the fact that I could achieve the same result with a for loop. I find the foreach loop more readable.

First we need to create a basic DateRange class. A range can be defined as a StartDate and an EndDate, so I’ll start there.

public class DateRange
{
    public DateRange(DateTime startDate, DateTime endDate)
    {
        StartDate = startDate;
        EndDate = endDate;
    }
 
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
}

So this DateRange could be useful on its own, but we want to be able to iterate this collection using a foreach. So to start we need to implement the IEnumerable<DateTime> interface.

public class DateRange : IEnumerable<DateTime>
{
    public DateRange(DateTime startDate, DateTime endDate)
    {
        StartDate = startDate;
        EndDate = endDate;
    }
 
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
 
    public IEnumerator<DateTime> GetEnumerator()
    {
        return new DateRangeEnumerator(this);
    }
 
    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

 

Notice here that we now need to get the IEnumerator<DateTime> object in the GetEnumerator() method. I jumped the gun a bit and I’ve called a class that doesn’t exist yet. I’ll make another class and implement the required methods for the IEnumerator interface.

public class DateRangeEnumerator : IEnumerator<DateTime>
{
    private int _index = -1;
    private readonly DateRange _dateRange;
 
    public DateRangeEnumerator(DateRange dateRange)
    {
        _dateRange = dateRange;
    }
 
    public void Dispose()
    {
    }
 
    public bool MoveNext()
    {
        _index++;
        if (_index > (_dateRange.EndDate - _dateRange.StartDate).Days)
            return false;
        return true;
    }
 
    public void Reset()
    {
        _index = -1;
    }
 
    public DateTime Current
    {
        get { return _dateRange.StartDate.AddDays(_index); }
    }
 
    object IEnumerator.Current
    {
        get { return Current; }
    }
}

 

These are the handful of methods we implement for the IEnumerator<DateTime> interface. These are all about moving to the next object and getting the current object. Resetting and Disposal of the object are less important, so make sure you read MoveNext and Current.

Keep in mind here that I could have used a collection for this, but I didn’t because I don’t need one. The calculation to get the items was easy enough.

var dateRange = new DateRange(DateTime.Today.AddDays(-6), DateTime.Today);
foreach (DateTime date in dateRange)
{
    Console.WriteLine(date.ToShortDateString());
}

Output:

10/20/2009
10/21/2009
10/22/2009
10/23/2009
10/24/2009
10/25/2009
10/26/2009