XAM’s Favourite (New) C# Features

At XAM Consulting (Xamarin Developers) our developers love to stay on top of the current trends in all aspects of software and mobile development. Last week we had a slack conversation geeking out about our favourite new C# features. I thought it would be nice to share some of the new features we love.

Majority of the features are C#7 and you can use them right now, in Xamarin and .NET.

Alfon

My favourite c# feature is the default implementation for a interface. This is my favourite because it solves the problem of developers of duplicating code implementations for an interface while still getting the power of multiple inheritance of it.

public interface IDocumentTransfer
{
    void TransferObject();
    void ConnectToStorage() 
    {
        PerformConnect();
    }
}

Jesse & Matthew Robbins

Oh yeah! My favourite C# 7 feature is `out var`s’ (Out variables)

public bool Validate(string input, out string message)
{
    // ….
}
//Usage
var result = Validate("Hello World", out var failureReason);

I love it as it saves an unnecessary variable declaration. Instead you can just inline it

I also love the `if (type is SomeOtherType someOtherType)` syntax for checking typecasts

Matthew B

The nameof operator which we now use extensively. It’s subtle but powerful because helps rid your codebase of those string literals. Yay.

EmailPlaceholderColor = Consts.ErrorColor;
RaisePropertyChanged(nameof(EmailPlaceholderColor));

Alex

Tuples and Deconstructing

(string, bool) EnsureMaxLength(string input) =>
    input.Length <= 5 ? (input, false) : (input.Substring(0, 5), true);

// Don't care if the value was trimmed or not, using "discard" variable name (underscore symbol):
var (processedVal, _) = EnsureMaxLength("abcd");

// Can check whether the value was trimmed by inspecting wasTrimmed variable:
var (processedVal2, wasTrimmed) = EnsureMaxLength("abcdef");

Martin

The inline getter arrow (“expression-bodied members”).

public bool IsOptionActive { get; set; }
public ImageSource OptionImage => IsOptionActive ? “Option_Enabled” : “Option_Disabled”; (edited)

Myself (Michael)

Personally I love the new ability to assign variables using the is statement with pattern matching.

private static void PrintObject(dynamic x)  
{  
    if (x is Customer c)  
    {
        WriteLine($"Customer Id : {c.Id} Customer Name {c.Name}");  
    }
}

In my years I’ve met many developers who don’t keep up with the new releases of languages, this is a little unfortunate for them because these new features help make code cleaner, more concise and increases readability.

This content originally appeared on the XAM Consulting – Blog.

Leave a Reply