Working with generic types in C#

in programming •  7 years ago 

Using Generic types in code is a simple enough concept. You can take all those duplicated code patterns in your code base and remove the type details. You can then use it instead of the duplicate code.

I will show their power with something I have used in production code before the ?. operater was added to the language.

We have all seen the classic pyramid of doom. Say you are extracting data from a structure you know might be incomplete. You end up with stuff this code vomit :)

string postcode = null;
if (person.Addresses != null 
{
    var homeAddressDetails = person
        .Addresses
        .FirstOrDefault(x => x.Type == Home);

    if (homeAddressDetails != null)
    {
        postcode = homeAddressDetails.Postcode;
    } 
}

To cut to the chase, here is the latest C# syntax for the same code using the ?. operator.

var postcode = person
    .Addresses
    ?.FirstOrDefault(x => x.Type == Home)
    ?.Postcode;

Before then I used the following. Here I have extracted the "if null" checks into a function. A half way house between the vomit code and the nice modern syntax.

public static TResult With<T, TResult>(
    this T container, Func<T, TResult> selector)
    where T : class
{
    return container != null
        ? selector(container)
        : default(TResult);
}

The generic types T and TResult can be called anything. I use T by convention to signify a type.

There where clause means the type T has to be a reference type.

So what does that give us...

var postcode = person
    .Addresses
    .With(as => as.FirstOrDefault(x => x.Type == Home))
    .With(a => a.Postcode);

As you can see. Smart uses of generic functions can make your life at the code face so much better :)

Happy coding

Woz

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!