using Programming;

A Blog about some of the intrinsics related to programming and how one can get the best out of various languages.

Doing Bad Cookie Authentication, but for the Right Reasons

Poor Cookie-Based Authentication with ASP.NET

Greetings everyone. Once again, it's been a while since I've posted anything. I've been swamped with work, personal issues, and then some. I got a new dog (hi Max!), and so on. Fortunately, I have a topic I want to talk about (you can probably guess based on the title what it is), and thanks to a friend of mine, who we'll call "Jim" becasue, well, that's his name, who asked about this on Twitter, I figured we could go all-in.

Disclaimer: I'm a rambler, and this was hastily written.

Jim was asking about cookie-based authentication in ASP.NET, which is a great topic because it's something you should absolutely never do, but we are going to do to help him demonstrate how such a thing can be used for test automation. (Jim is a VERY smart person, and is working up a demo on how we can use cookie authentication hand-in-hand with test automation to do a wide-variety of things. The idea is to allow a test client to authenticate itself to quickly and easily get into the application.) We're going to spend this whole blog-post going over a worst-practice, vs. a best-practice. We're going to do all the things I always say never do, and learn why. (There's a lot of reasons we should not do any of these things, I'll try to cover a few with some examples.)

Then, at the end, I'm going to show you how we could do this type of authentication easily and via some sort of API call, so that we could stick with the core authentication principles that we value, and also satisfy our testers. This will demonstrate where the testers and the developers should be able to work together, to develop a flow that works for both.

We're going to build this out in Visual Studio, as usual, and we'll go over how we can take a blank ASP.NET website and add cookie-based authentication. Typically, we would use Forms-based authentication, or Active Directory / Windows Authentication.

What is a cookie?

A cookie is a small (usually) piece of information that a users browser stores which allows them to carry and pass information to and from a website. This cookie is a piece of data that is sent client-to-server, and server-to-client. We use cookies to transfer non-confidential data, because cookies are incredibly insecure. Anyone can spoof a cookie, and we'll look at doing exactly that in this blog post as well.

Cookie-Based Authentication in ASP.NET

Alright, so let's go ahread and create some cookie-based authentication in our ASP.NET application. For this, we'll have three pages:

  • Default.aspx: the main landing page, visible to authenticated and unauthenticated users;
  • Login.aspx: the login page, this will test the user login and create an appropriate cookie;
  • Authenticated.aspx: a page only available to authenticated users;

Step 1: Create the Authenticated.aspx

This page is pretty basic markup-wise (even code-wise):

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Authenticated.aspx.cs" Inherits="Poor_Cookie_Authentication__17_4_2018_.Authenticated" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            Hello <asp:Literal runat="server" ID="litUserName"></asp:Literal>!
        </div>
        <div>
            This page is only available to authenticated users.
        </div>
    </form>
</body>
</html>

Basically, we throw a single literal which will be the name of the authenticated user. We'll populate this from the code-behind file, which is also really simple. But, before we do the code-behind, let's build a user object.

I'm going to do extremely basic authentication: our User class will have a Username (email) and Password. It will also contain a static array of all eligible users, so as to allow us to "pretend" to log someone in. We'll create two sample users, with different passwords:

public class User
{
    public static User[] Users { get; } =
        new[]
        {
            new User() { Username = "ebrown@example.com", Password = "1234" },
            new User() { Username = "johndoe@example.com", Password = "5678" }
        };

    public string Username { get; private set; }
    public string Password { get; private set; }
}

This can be replaced with any type of user loading, but I kept it simple to allow easy demonstration.

Now, let's load the user:

public partial class Authenticated : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.Cookies["UserId"]?.Value == null)
        {
            Response.Redirect("Login.aspx");
        }

        var userId = int.Parse(Request.Cookies["UserId"].Value);
        var user = Models.User.Users[userId];
        litUserName.Text = user.Username;
    }
}

So, if it's not apparant, cookie reading is super simple in ASP.NET: simply call Request.Cookies[name].Value, I use ?.Value to avoid the need for an additional null-check. (If the cookie doesn't exist, Request.Cookies[name] returns null instead of throwing a KeyNotFoundException like a normal dictionary would.)

Step 2: Login.aspx

Alright, so the next step is to allow the user to login. This is really simple, and we'll do it with a small HTML page and code-behind. The login will take a username and password, and match that to a user in the User.Users array. If we find one, set a cookie with the ID.

Markup:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="Poor_Cookie_Authentication__17_4_2018_.Login" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Literal runat="server" ID="litError"></asp:Literal><br />
            Username: <asp:TextBox runat="server" ID="txtUsername" TextMode="Email"></asp:TextBox><br />
            Password: <asp:TextBox runat="server" ID="txtPassword" TextMode="Password"></asp:TextBox><br />
            <asp:Button runat="server" ID="btnSubmit" OnClick="btnSubmit_Click" Text="Login" />
        </div>
    </form>
</body>
</html>

Code:

public partial class Login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.Cookies["UserId"]?.Value != null)
        {
            Response.Redirect("Authenticated.aspx");
        }
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        var username = txtUsername.Text;
        var password = txtPassword.Text;

        var user = Models.User.Users.FirstOrDefault(x => x.Username == username && x.Password == password);
        if (user != null)
        {
            Response.Cookies.Add(new HttpCookie("UserId", Models.User.Users.ToList().IndexOf(user).ToString()) { Expires = DateTime.Now.AddHours(8) });
            Response.Redirect("Authenticated.aspx");
        }

        litError.Text = "The username/password combination you entered does not exist.";
    }
}

There are two ways to set a cookie:

  • Use Response.Cookies.Add;
  • Directly call to Response.Cookies[name], which will create the cookie if it does not exist;

Here, I chose the former as it's clearer. We add a new response cookie, set the expiration for 8 hours from now, and then redirect the user to the Authenticated.aspx page.

Step 3: Our Default.aspx with logout

The last step here is to make our Default.aspx page, which is again simple, and perform our logout on this page.

Markup:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Poor_Cookie_Authentication__17_4_2018_.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:HyperLink runat="server" ID="hlLogin" Text="Login" NavigateUrl="~/Login.aspx"></asp:HyperLink>
            <asp:LinkButton runat="server" ID="lbLogout" Text="Logout" OnClick="lbLogout_Click"></asp:LinkButton>
        </div>
    </form>
</body>
</html>

Code:

public partial class Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.Cookies["UserId"]?.Value == null)
        {
            lbLogout.Visible = false;
        }
        else
        {
            hlLogin.Visible = false;
        }
    }

    protected void lbLogout_Click(object sender, EventArgs e)
    {
        Response.Cookies["UserId"].Expires = DateTime.Now.AddDays(-1);
        Response.Redirect("Default.aspx");
    }
}

We literally have a "Login" and "Logout", which one is shown depends on whether or not the cookie is set. On logout, we set the cookie expiration to the past so that the browser will delete it, and redirect the user.

Authentication complete!

Alright, so all-in-all we're basicallly done with designing the cookie-based authentication of the application, now let's move on to the insecurities of it.

Cookie-Based Authentication Insecurities

There are literally hundreds of things we could list that are reasons to not use cookie-based authentication, but let's just go over some of the basics:

  • Cookies are handled entirely client-side. That means, the client must be trusted to track the entire lifetime of the cookie: value, expiration, etc., all of it is in the client's hand.
  • Cookies are always plain-data. That is to say, they are not secured in any manner. In a non-HTTPS environment, cookies are clearly visible on transmission from client-to-server, and server-to-client. A man-in-the-middle attack with cookies is so unbelievably easy. (Facebook used to be vulnerable to session-hijacking using this attack, and I'll pull references on that later.)
  • Cookies carry small amounts of data. There are limits to the size of a cookie, due to the nature of it. Because cookies are passed in the headers of a web request or response, they are limited to the maximum size of a header.

Alright, so let's exploit some cookie insecurity. We're going to do four things:

  1. Change the expiration to keep ourselves logged in longer;
  2. Change the user ID to log in as someone else;
  3. Change the user ID to cause the server to error (if you place cookies into SQL this can do really bad stuff);
  4. Create a cookie with a user ID to login without credentials;

So the first task on our to-do list is to change a cookie expiration. We set it for 8 hours, but any sufficiently skilled user (and you really don't have to be all that skilled) can alter it. In fact, if you download the EditThisCookie plugin for Opera, you can do so with a two clicks. I'm going to use this to do the rest, and I'm just going to throw all the pictures with basic captions.

Step 1: We'll Login via Opera. That "Cookie" icon is our editor.

Opera Login

Step 2: Open the cookie. We click the "Cookie" Icon and expand the cookie we want ("UserId").

Opening the Cookie

Step 3: Edit the Expiration and click the "Checkmark" to save.

Edit Expiration

As you can see, pretty easy.

Next, we'll edit the value to be someone else:

Edit Value

New Page

Now I did not relogin, I used the original login and edited who I was. That's important to remember because it demonstrates why this is insecure.

We can error the server:

Bad Cookie

And even make a new cookie without logging in:

New Cookie

Automating our Tests

Ok, on to the fun part: let's automate a login, but without ever hitting the login page or function.

This is almost too easy with .NET, we'll use the WebClient and manually send the Cookie header. To do this, I created a TestAutomation.aspx page:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TestAutomation.aspx.cs" Inherits="Poor_Cookie_Authentication__17_4_2018_.TestAutomation" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Literal runat="server" ID="litResponseData"></asp:Literal>
        </div>
    </form>
</body>
</html>

The code is trivial:

public partial class TestAutomation : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        using (var wc = new WebClient())
        {
            wc.Headers.Add("Cookie", "UserId=1");
            litResponseData.Text = wc.DownloadString("http://localhost:60078/Authenticated.aspx");
        }
    }
}

Yes, we logged in and downloaded the Authenticated.aspx text with 5 lines of code, 2 of which were braces. By manualy sending the header, we made it too easy for us to work with.

If you comment out the wc.Headers.Add line, you'll see that it returns the login form. This is because the WebClient follows the redirects. With that line in, we get the Hello ...! message.

An Ideal World

Alright, so all of this is done to demonstrate the point of how easy it is to use cookie-based authentication, and how we can exploit it, but also the ease of which it does what we want. One of the things Jim had mentioned to me was that he wanted the ability to either turn authentication off, or some other way to allow the user to login, but without needing to do too much complex work.

Typically, in this scenario, this is where the developer and tester would work together on a solution, one of which might be a very simple API call to do login: pass a username and password, then it logs that session in. We can simulate this by accepting Username and Password query-string parameters in our Login.aspx:

public partial class Login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["Username"] != null && Request.QueryString["Password"] != null)
        {
            var username = Request.QueryString["Username"];
            var password = Request.QueryString["Password"];
            doLogin(username, password);
        }

        if (Request.Cookies["UserId"]?.Value != null)
        {
            Response.Redirect("Authenticated.aspx");
        }
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        var username = txtUsername.Text;
        var password = txtPassword.Text;
        doLogin(username, password);
    }

    private void doLogin(string username, string password)
    {
        var user = Models.User.Users.FirstOrDefault(x => x.Username == username && x.Password == password);
        if (user != null)
        {
            Response.Cookies.Add(new HttpCookie("UserId", Models.User.Users.ToList().IndexOf(user).ToString()) { Expires = DateTime.Now.AddHours(8) });
            Response.Redirect("Authenticated.aspx");
        }

        litError.Text = "The username/password combination you entered does not exist.";
    }
}

So Login.aspx didn't change much, we just handle both cases now. By pushing login into a function, it made it easy to deal with the query-string based login, and the form-based login. We need to modify our TestAutomation.aspx page a little to accommodate:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TestAutomation.aspx.cs" Inherits="Poor_Cookie_Authentication__17_4_2018_.TestAutomation" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Literal runat="server" ID="litResponseData1"></asp:Literal><br /><br />
            <asp:Literal runat="server" ID="litResponseData2"></asp:Literal>
        </div>
    </form>
</body>
</html>

The code is the big change:

public partial class TestAutomation : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // Method 1
        using (var wc = new WebClient())
        {
            wc.Headers.Add("Cookie", "UserId=1");
            litResponseData1.Text = wc.DownloadString("http://localhost:60078/Authenticated.aspx");
        }

        // Method 2
        var cookieContainer = new CookieContainer();
        var req = WebRequest.CreateHttp("http://localhost:60078/Login.aspx?Username=ebrown@example.com&Password=1234");
        req.CookieContainer = cookieContainer;
        req.GetResponse(); // We don't need to do anything with the response

        req = WebRequest.CreateHttp("http://localhost:60078/Authenticated.aspx");
        req.CookieContainer = cookieContainer;
        var response = (HttpWebResponse)req.GetResponse();
        using (var sr = new StreamReader(response.GetResponseStream()))
        {
            litResponseData2.Text = sr.ReadToEnd();
        }
    }
}

You see the // Method 2 comment? That is the part that uses the query-string to login. It can also use a POST to a form to login, if we wanted, though that is far more complex. Due to the ASP.NET event validation, it is far easier to virtually create the UI form in that case, and submit it. Instead, what we did is query-string based to support the testers use-case, and make it easy to do the testing, while also retaining most of our security.


This project is available on GitHub and I am allowing anyone to use it to any purpose, I simply ask that if you use the project directly, throw some sort of nice message on where you found it.

Demonstrating Insecurity of Managed Windows Program Memory

Is Memory in a Managed Windows Program Secure?

Recently I was on one of the (many) Stack Exchange sites answering a question a user posted, like usual. This question was a bit different though: the asker was concerned about the best way to make sure people couldn't read the password the user entered out of memory.

Unfortunately, this is not a task that can really be solved on consumer devices. Anyone with enough knowledge (and it's not really a lot) can do it. I'm going to demonstrate how to today with a simple Visual Studio programme.

Essentially, what I'm going to do is 'connect' to a fake SQL server (nothing about it will really exist) and then demonstrate how one can (with a copy of Visual Studio) extract the entire Connection String of that SQL connection out. It's actually quite trivial and with enough practice can be done in seconds.

Of course there are other ways to do this, it can be done programatically, there are other bits of software for it, etc. I'm just going to demonstrate how any developer can do it with the tools (s)he has at their disposal.

Creating our test projects

So the first step is to create a test project we can use to 'attack'. We're going to consider this an attacker/victim scenario, since that's what one of the real world applications is.

Our code is going to be pretty simple:

using Evbpc.Framework.Utilities.Prompting;
using System;
using System.Data.SqlClient;

namespace VictimApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            var consolePrompt = new ConsolePrompt(null);

            var connectionString = new SqlConnectionStringBuilder();
            connectionString.DataSource = consolePrompt.Prompt<string>("Enter the SQL server hostname/ip", PromptOptions.Required);
            connectionString.UserID = consolePrompt.Prompt<string>("Enter the SQL server user id", PromptOptions.Required);
            connectionString.Password = consolePrompt.Prompt<string>("Enter the SQL server password", PromptOptions.Required);
            connectionString.InitialCatalog = consolePrompt.Prompt<string>("Enter the SQL server database", PromptOptions.Required);

            using (var sqlConnection = new SqlConnection(connectionString.ToString()))
            {
                try
                {
                    Console.WriteLine("Connecting...");
                    sqlConnection.Open();

                    using (var command = new SqlCommand("SELECT 15", sqlConnection))
                    {
                        Console.WriteLine($"Command output: {command.ExecuteScalar()}");
                    }
                }
                catch
                {
                    Console.WriteLine("Could not establish a connection to the server.");
                }
            }

            Console.WriteLine("Press enter to exit.");
            Console.ReadLine();
        }
    }
}

Do note this uses my ConsolePrompt from GitHub.

So we have our victim application, now we'll go ahead and attack it.

Attaching Visual Studio to a running application

You're probably expecting a title like 'attacking an application with Visual Studio' but that's not as descriptive as what we're doing. Yes, this is how you attack it, but attack sounds nefarious. We're not doing anything nefarious, we're just attaching a debugger to a running application.

So we're going to open a new instance of Visual Studio, and not open or create a project. Just open the instance.

Screenshot 1 - Fresh Visual Studio Instance

So, we've opened Visual Studio (I'm using 2015 but this should work on 2010+). The next thing we'll do is launch our application.

Screenshot 2 - Launch Application Outside Debugger

Right, so we have the application running outside the debugger. No other instances of Visual Studio need to be open, nothing else needs to be running, just that application and our fresh instance. The next step is to attach the debugger to a process.

This is under Debug -> Attach to Process. You should see a new window open, and we want to find our 'Victim Application' (VictimApplication.exe).

Screenshot 3 - Attach to Process

We'll go ahead and attach it. Our screen should change to look like we're in a regular debug session, even though we didn't launch the program through Visual Studio.

Screenshot 4 - Debug Session is Green err Blue

Now we still have our other window open with our running application in it. All we have to do next is start checking it out and see what we can inspect.

This next part isn't required, but it should help you familiarize yourself with what we're going to do. Let's hit the 'Break All' button (CTRL + ALT + Break with default shortcuts).

Screenshot 5 - Break mode

As of this moment the program is paused. Since it's a console application, you can still type into it, but your typing will not be processed by the program at this point.

Screenshot 6 - Text not handled by program

Next we'll hit 'Show Diagnostic Tools' and then select the 'Memory Usage' tab. Once we have done that, we'll hit 'Take Snapshot'.

Screenshot 7 - Taking our first memory snapshot

So now we're at the point we can start inspecting objects in our program. The first thing we'll want to do is click the blue 429 (your number may vary) link to the list of objects.

We'll then sort them by name since we're not concerned about the count, we just want to look through them.

I'm going to inspect our ConsolePrompt as an example, which in this case is listed as Evbpc.Framework.Utilities.Prompting.ConsolePrompt. When you find an object you want to inspect, hover over it and you should see an icon that looks like a square grid with a circular shape on the top-left corner, click that and a new page should open.

Screenshot 8 - Selecting an object to inspect

We'll then see a new page with all the instances of that object listed. If you hover over the Value, you should get a tool-tip that has a breakdown of the object itself, which you can explore just like normal. We'll see that the Logger is in fact null like we wanted.

Screenshot 9 - Exploring our object

Now that we've played with our explorer, we can go ahead and close that breakdown and continue with our program. We'll hit 'Continue' and resume execution. If you typed a server host into the console, you'll see as soon as we hit continue that the program continues to the next step. We'll fill out all our requirements and then break our program again when it starts connecting, and take another memory snapshot.

Screenshot 10 - Connecting to our server

We see that the new snapshot has 3,825 objects allocated, and the difference is an increase of 3,396. Our graph shows that we allocated a lot more memory (relatively speaking) and we can now go ahead and inspect our snapshot to try to find our password. We'll be looking for a string type with a value of pass.

We know it'll be part of the SqlConnection, so we'll sort that by name and then go down to SqlConnection and explore it like before.

Screenshot 11 - Find our SqlConnection

Upon exploring it we'll just a different method of extracting our string. Click 'Referenced Objects' at the bottom of our window, and hover over the middle String object. (Mine is 0x2FB0BD8)

Screenshot 12 - Extracting our Connection String

And there we have it. We have successfully extracted our password from a separate Visual Studio instance while the original application was running completely separately.

Debug Symbols and why they are important

Of course, our demonstration was made slightly easier by the inclusion of the .pdb files (debug symbols), usually you won't have access to these for the running application, so you'll have to look a little harder sometimes to find what you're looking for.

If you don't know what Debug Symbols are, Wikipedia has a nice description. Essentially, the pdb file (stands for 'Program Database') is the symbol map for .NET programs. It contains each generated instruction header and what the generated name of it was.

Finding our String without SqlConnection

The last thing we'll do is find our string value without exploring the SqlConnection object. We're only going to look with the Diff list, and run from there.

So, we'll restart our application, then attach the debugger, then enter our host and user, then take a memory snapshot like we did earlier.

Screenshot 13 - Round 2 First Snapshot

Then we'll hit 'Continue', enter our password, and take another snapshot.

Screenshot 14 - Round 2 Second Snapshot

The next step is to disable 'Just My Code' in the filter. If we don't do this it becomes much more difficult to locate what we changed.

Screenshot 15 - Round 2 Disable Just My Code

So we see that it created one string, by the Count Diff. being +1 on the String type, this helps us narrow down what we're looking for. If click once into it, and view our 'Paths to Root', it helps us discover that we have +1 in String [Local Variable]. So we're in the right place.

Screenshot 16 - Round 2 String Local Variable

We'll inspect the String like before (Square icon with Round outset) and we'll see that by default it sorts the list by `'Inclusive Size (Bytes)', we'll sort it by 'Instance'. Theorhetically our password should be the last instance listed. If we scroll to the bottom of the list we see that, indeed, it is.

We also see that our user id is right above it.

Screenshot 17 - Round 2 Find our Password


And there we have it! We learned how to inspect objects in our program when it was launched outside Visual Studio by attaching a debug instance of Visual Studio to it.

C# Expression-Bodied Members

Using Expression-Bodied Members in C#6.0

So it's been a while since I've written a blog post (far too long if you ask me). I'll not go into too much detail, but I've been busy doing some life things. I recently changed jobs, moved, and started working on a great deal of other projects that just consume all my time, and I haven't had time to share any of my thoughts recently.

With that said, I do have something I wish to talk about at the moment, and that is a new feature found in C#6.0: Expression-Bodied Members.

This feature, in my opinion, is one of the more useful features of the recent language update. It opens a great deal of doors and has shortened a lot of my code substantially, which is always good. (For some reason, we strive to keep the number of characters/lines on our source code to a minimum.) It offers us the ability to take certain methods and properties, which would have otherwise taken up a fair amount of space, and shrink them down to a much more manageable level.

However, before we talk about this feature, we need to talk about all the parts of it. So let's begin with the most important part of an expression-bodied member: the expression.

What is an expression?

We're going to take a definition from webopedia (see http://www.webopedia.com/TERM/E/expression.html) which should sum it up fairly well:

In programming, an expression is any legal combination of symbols that represents a value.

This is a pretty basic definition, but should work to serve our needs quite well. When we use the term expression we mean a fairly simple set of instructions that return a value. Do note: I bolded "return a value" for a reason. If the set of instructions do not return a value, then they are not an expression, and cannot make up an expression-bodied member. (We'll see this isn't entirely true shortly.)

A few examples of what we mean by expressions when discussing them in C#:

2 + 5
x * 4
"EBrown"
name ?? "No Name"
person.ToString()

The last one might surprise you - yes, calling .ToString() on something is an expression, as .ToString() returns a value. The second-to-last might surprise you as well, but it's pretty simple: if name is null, then the expression evaluates to "No Name".

Do note: expressions don't have to return a non-null value. The person.ToString() call above could potentially return a null value, and that's perfectly OK. It's still an expression. The value itself has no bearing on the definition of the term, only whether or not something actually returns a valid value. This is an important concept to bear in mind, as not all of our expressions have non-null values.

So what do expressions usually look like in C#?

Any series of tokens that follow a return token, up to the first subsequent semicolon (;) are an expression. So for all of our examples above, they might look like:

return 2 + 5;
return x * 4;
return "EBrown";
return name ?? "No Name";
return person.ToString();

Mind you, expressions don't have to follow a return statement. Consider that 2+5 is still an expression in the following example:

var myString = "Some string " + (2 + 5).ToString() + " with numbers in it.";

But we also have several other expressions:

2 + 5
(2 + 5).ToString()
"Some string " + (2 + 5).ToString() + " with numbers in it."

All three of these are expressions, in their own right. All three of them also contain other expressions. This is an important concept to understand, in the expression 2 + 5, there are actually two other expressions: 2 and 5. These are both expressions as well.

What does an expression-bodied member look like, in C#?

There are two types of expression-bodied members in C#:

  • Expression-bodied readonly properties;
  • Expression-bodied methods;

Both types of expression-bodied members in C# look something like the following:

member => expression;

It's very simple, you provide a member, the "lambda" sign (=>), and an expression. You can also provide the standard member modifiers in the member itself as well. (Access modifiers, attributes, etc.) It's a regular member, it just uses a different body syntax. You should note that there are no braces in play, it's just a member and expression.

An example of a C# expression-bodied member:

public override string ToString() => $"Name: {Name}";

Note that there is no return statement. An expression-bodied member always returns a value. (Except in the case of void methods.) That is why we just talked about expressions to such detail. We need something to return. Something to give back.

What about void methods?

You can still use an expression-bodied member in a void method, it simply has to have a void return type, or be a disposable call. The following code is completely valid C#6.0:

public void MethodA() { }
public void MethodB() => MethodA(); // `MethodA()` is `void`, and `MethodB()` is `void`
public string MethodC() { return "MethodC"; }
public void MethodD() => MethodC(); // The result of `MethodC()` is disposable

The following is invalid:

public void MethodA() { }
public string MethodB() => MethodA(); // The expression returns a `void` type, but a `string` is expected
public void MethodC() => "MethodC"; // The expression returns a `void` type, but the value is not disposable

An expression-bodied member with a return type can mentally be rewritten as:

member { return expression; }

An expression-bodied member with a void return type can mentally be rewritten as:

member { expression; }

How do I use expression-bodied members?

It's pretty simple to use an expression-bodied member. You have two options: an expression-bodied readonly property, and an expression-bodied method. Both of these are trivial to use, the only difference is a minor issue in syntax.

Just like a normal readonly property, and expression-bodied readonly property only has a get-method within it. The difference is syntax. As we may recall, a normal readonly property may look something like:

public double TotalPrice { get { return Quantity * Price; } }

To convert this to an expression-bodied member, we simply replace the getter with an expression of the previous syntax:

public double TotalPrice => Quantity * Price;

This is a property bodied by an expression. You'll note that there are no parameters passed, so as far as other code is concerned it's treated just like a normal property, that only has a getter.

The only difference between a method and a property being bodied by an expression is that a method has the requisite parenthesis in the definition.

public override string ToString() { return $"Price: {Price}, Quantity: {Quantity}"; }

As a method, could be rewritten as:

public override string ToString() => $"Price: {Price}, Quantity: {Quantity}";

As you can see, in both cases we omitted the return altogether. Properties and methods that specify a non-void return type implicitly return whatever the result of the expression is.

A real life example of the benefits of expression-bodied members

For this I'm going to use a partial copy of a class I wrote for a C# library I'm working on. (I'm omitting all the comments and attributes, for brevity.)

This is (most of) a Rectangle class I wrote in a drawing library (for a clone of Windows Forms for XNA). This first version is the version without expression bodied members at all. You can find the most recent version at: https://github.com/EBrown8534/Framework/blob/master/Evbpc.Framework/Drawing/Rectangle.cs

public struct Rectangle
{
    public Rectangle(Point location, Size size)
    {
        Location = location;
        Size = size;
    }

    public int Bottom { get { return Location.Y + Size.Height; } }
    public bool IsEmpty { get { return this == Empty; } }
    public int Left { get { return Location.X; } }
    public Point Location { get; }
    public int Right { get { return Location.X + Size.Width; } }
    public Size Size { get; }
    public int Top { get { return Location.X; } }

    public override bool Equals(object obj) { return obj is Rectangle && (Rectangle)obj == this; }
    public override int GetHashCode() { return base.GetHashCode(); }

    public override string ToString()
    {
        return $"({Location.X},{Location.Y},{Size.Width},{Size.Height})";
    }

    public static bool operator ==(Rectangle left, Rectangle right)
    {
        return left.Location == right.Location && left.Size == right.Size;
    }

    public static bool operator !=(Rectangle left, Rectangle right)
    {
        return left.Location != right.Location || left.Size != right.Size;
    }

    public static readonly Rectangle Empty = new Rectangle(0, 0, 0, 0);
}

Pretty simple, right? I'm not going to discuss any of the other C#6.0 features that I've used, just know that there are some.

Now, let's see what this looks like if we replace all the smaller methods with expressions.

public struct Rectangle
{
    public Rectangle(Point location, Size size)
    {
        Location = location;
        Size = size;
    }

    public int Bottom => Location.Y + Size.Height;
    public bool IsEmpty => this == Empty;
    public int Left => Location.X;
    public Point Location { get; }
    public int Right => Location.X + Size.Width;
    public Size Size { get; }
    public int Top => Location.Y;

    public override bool Equals(object obj) => obj is Rectangle && (Rectangle)obj == this;
    public override int GetHashCode() => base.GetHashCode();
    public override string ToString() => $"({Location.X},{Location.Y},{Size.Width},{Size.Height})";
    public static bool operator ==(Rectangle left, Rectangle right) => left.Location == right.Location && left.Size == right.Size;
    public static bool operator !=(Rectangle left, Rectangle right) => left.Location != right.Location || left.Size != right.Size;

    public static readonly Rectangle Empty = new Rectangle(0, 0, 0, 0);
}

A little cleaner, yes? The horizontal space of our code has been significantly reduced for most of the methods and properties. A lot of that clutter is now gone.

Limitations of Expresison-Bodied Members

One of the major limitations of expression-bodied members is exception throwing. Exceptions cannot be thrown directly from an expression-bodied member. You can still do things that would throw exceptions, but you cannot actually throw anything. This is due to the fact that throw ... is a statement, rather than an expression.

See this Stack Overflow question and answer for more information on this limitation.

DO's and DON'Ts of Expression-Bodied Members

Here are a few of the general do's and don'ts I use when determining if I can use an expression-bodied member:

  • DO use expression-bodied members on non-auto-implemented readonly properties

    • This helps reduce clutter in code and makes the intention much more explicit. It allows future programmers to see that the property was meant to be explicitly readonly, and that a set clause should never appear for it.


  • DON'T use expression-bodied members on static readonly fields (Empty, etc.)

    • Any static readonly fields should be simple values, which should never change. By rewriting them as expression-bodied members, these simple fields are now properties, and as such slightly more overhead is attributed to them. (Especially in the case of Empty fields.)


  • DO use expression-bodied members on methods with simple return statements

    • Methods that have a single return statement written as expression-bodied methods allow the programmer to be completely explicit about the intention of the method.


  • DON'T use expression-bodied members when the expression contains multiple ternary or null-coalescing operators

    • Expression-bodied members may be used when one of either (or one of both) is found, but should not be used if more than one of either of these is found. This creates confusion and makes debugging the method much more difficult.

And the last one, which you may or may not want to adopt (I have):

  • DON'T use expression-bodied members on void methods, period

    • In the case of void methods, an expression-bodied method is misleading. It tends to hint at the idea that something should be returned (as expressions should always return a value) when in fact nothing is to be returned, by design. It creates confusion among developers.