Taswar Bhatti
The synonyms of software simplicity
Csharp-MS-Dotnet

In C#7 there is an improvement on using out parameter. Some of you may remember writing code like below.

The improvement that C#7 brings is you can now declare out variables in the argument list of a method call, rather than writing a separate declaration statement like below:

And it doesn’t end there we can also use the var keyword if we choose to.

Summary

What are the benefits of this out parameter, well it does make the code is easier to read. You are not declaring it where you use it. Not to mention you don’t need to initialize the variable either.

Csharp-MS-Dotnet

In C# 7 there the new feature called Local functions in C#. Basically Local functions allow one to write a function within the body of another method or function. It comes in handly in the case lets say you are creating a helper function that are mostly just used in one class or where the declaration makes the code clear of the intention. Local functions also come in handly to write recursive functions rather than using a Lambda for it.

Here are some places where you can use local functions.

  • Methods, especially iterator methods and async methods
  • Constructors
  • Property accessors
  • Event accessors
  • Anonymous methods
  • Lambda expressions
  • Finalizers
  • Other local functions

Below is an example where I Anonymize a string of emails, you can see that I am actually calling the local function below the return statement. Therefore where you can declare a local function below a return statement and also the Pattern variable is available inside the local function, since it is within its scope.

If you wish to read more on local functions take a look at the Microsoft documentation of local functions.

Csharp-MS-Dotnet

In C# 7 there are Expression Bodied Accessors which allows you to write getter and setters somewhat more functional way, somewhat lambda’ish. Let me show you an example. You may remember the old way of writing getter and setters like below.

Pre Expression Bodied Accessors Getter and Setter

Expression Bodied Accessors in C# 7

When using C# 7 you can use Expression Bodied Accessors like below which makes the code wayyyyy cleaner in my opinion. As you can see below, I have also added the null exception into the setter.

Summary

I hope I have explained how Expression Bodied Accessors can make your code way cleaner and easier to understand, not to mention that you can include exception into the setter since Exceptions are also Expression now. If you wish to learn more you can also visit Microsoft Learn Site on Express Bodied Accessors. Btw you can also use the Expression Accessors for Constructors and Destructors.

Csharp-MS-Dotnet

In C#7 there are Digit Separators and Binary Literals which were added. One may wonder what these are? Basically you can replace long number values with underscore (_) such that code readability is improved.

Let me give you couple of examples of it to make it clear.

Neat but it doesn’t end there you can also use it for Binary literals and Hex also, like the examples below, where they all are 2020 the year we all despise 🙂

Summary

I hope the C#7 Digital Separators and Binary Literals will give you a hand in writing more clear code 🙂

Csharp-MS-Dotnet

So one may ask “What is the advantage of using discards in C#?”, and if you don’t know what discards are you can check out the MS C#7 Documentation about it.

Basically discards are variables in simple terms, and the declaration of the variable as a discard is by assigning it the underscore (_) as its name. Let’s look at an example of it using tuples. And if you want to know more about tuples look at my older post on tuples.

Example discard in C#

As you can see above I have declare lastname as a discard, the advantage is that the lastname variable may not even be allocated any storage. Thus in a sense discards can reduce memory allocations, that is one of the main advantage of discards. Not to mention that it the intent of the code above clearer, readability wise and maintainability wise. There are other places you can use discards also.

Out parameters methods

The code below shows using discard in a TryParse method like below, where we use the out method for getting the value, but if we don’t really care about the value discards comes in handy here.

Pattern Matching

One can also use discards in pattern matching in C#. In the below example I am using pattern matching to process a user where a user can be a student or partime student, and they both are process the same way for example.

Deconstruct method

In C# you can also use discards for deconstruct methods, where you use a method name Deconstruct with out parameters, let’s look at an example of it. It is another handy way to get data out of class, structures and get them into tuples.

Summary

I hope this helps in explaining where you can see potentials of using discards in C#, it is a way of intentionally not wanting a variable, the plus side of it, allows one to read the code more clearly.

Csharp-MS-Dotnet

Some may wonder what is the difference between ValueTuple and Tuple that was released in C# 7, and you might say I have been using Tuples for a while now. Whats the difference? Some of you will remember with code like below that showcase the use of ValueTuple since .NET Framework 4.7

In order to use this, you will use the data members, such as Item1, Item2, etc., which are fields rather than properties. So in your code it will look something like below. As you can see it pretty ugly and which one is firstname and which one is lastname? You will have to guess was it Item1 or Item2?

Main differences

The main difference between Tuple and ValueTuple are:

  • System.ValueTuple are structures (value types) rather than classes (reference types). This is meaningful when talking about allocations and Garbage Collection pressure.
  • System.ValueTuple are mutable rather than read-only. That is, the value of tuple components can change.
  • System.ValueTuple exposes data members, such as Item1, Item2, etc., are fields rather than properties.

Lets try to use the same example and use System.Tuple rather and see how our code changes.

In the above code you can see it’s shorter and clearer of the intention of the code and when we try to consume this code like below we can use the labels rather.

Summary

Hope you learned something new today and start using the new syntactic sugar that C# 7 provides, and if you are doing machine learning you will also feel the benefit of C# Tuples. More on machine learning in later blog post 🙂

WordpresstoGatsby

As we have got to know that Gatsby has built in GraphQL, we will learn this time how to ask Gatsby to request data from GraphQL. We will ask for the data that we wish to populate into our blog. For simplicity sake we will only target on the title and tagline. Eventually we will dive deep into into it later when we talk about plugins.

First we need to modify our gatsby-config.js file and add sitemap information into it. Below you will see that I have added a tag called SiteMetadata and inside the json object it contains title and tagline.

If we wish to view this data we can go to our trusty graphql site that Gatsby has created for us (http://localhost:8000/___graphql). We can query the data in the query field like below and we will get back a json object with the information.

gatsby-graphq-query

gatsby-graphq-query

How to get the data into our page

You are like great we have graphql but how do I get this data into my page? That is where graphql query inside our code comes in handy. Let open up our index.js that we have been working on and modify it to include graphql and we can also query it like the code below.

NOTE: Query only works in pages

NOTE: The single right tick quotes that encapsulates the query

We have also passed in {data} as a parameter into the Home function, we are able to print the data with the {} brackets. e.g {data.site.siteMetadata.title}, it is basically the same way we see the data in graphql UI.

How to share the data to components then?

One way to share data to component is to pass it down but then it becomes ugly quite soon, therefore there is actually another way to query data with components that is to use staticQuery, since page query are not supported in components. Let’s see that in action for our Layout component we made. Open the file components/layout.js

As you have noticed I have imported useStaticQuery and graphql into my javascript. I have also declared a const variable called data and have used it to pass the data to my header component and footer component. Again you can use the same query inside of component the only difference is that you can see above is I have wrapped it around useStaticQuery.

Summary

We talked about using Query to get data from GraphQL for our Gatsby site, where Query are only allowed in pages. We also talked about how we can use staticQuery to get data inside our components. In our next section we will talk about using source plugin with GraphQL power to get data from local filesystems, such that we can eventually read our blog post.

WordpresstoGatsby

We have our footer and header together and it’s time to talk about Layout. We can create a layout component in Gatsby such that our header and footer can be embedded/nested into any page you wish to have later on. Example our about, contact pages. This will allow us to clean up some of our page code.

Creating a layout in Gatsby with VSCode

We will create a component called component/layout.js inside the component folder. The code for layout is as below.

Couple of things you may notice, we are taking something called children into the parameter of the Layout component. This is a way for us to embed/nest more html components inside the layout. If we look at our example pages/index.js page we will see everything that is declared inside out page will be translated into children for the layout page. Thus having a header and footer page for them also. We have embedded content and sidebar div into the layout, which will result in Header and Footer to wrap them around, with the code below.

Now our page will look like the image below.

Header Footer with sidebar and content page

There are still couple of things to fix but we are getting there, and you may have notice that the data is being repeated in our layout. I think we can do better and Gatsby does allow us to do better with StaticQuery which we will cover next.

Summary

We talked about using layout component for our content so that we can use nested components for other pages. We have used the children parameter to pass in nested html components into our layout component so that we can embed other content into our page.

WordpresstoGatsby

Now that we have the header of the page, let’s try to focus on our footer. We will be creating a footer component in Gatsby with VSCode, we will skip the content and sidebar for the time being and get back to it later. Just like the header page we will create a new file called component > footer.js inside our component folder. We will again use css modules for our style called component > footer.module.css. Below is the code for the component > footer.js, as you can see it has clean html and I have removed a lot of redundant styles from wordpress.

Something you may note above is I am just using plain vanilla Javascript for the year where I have used {(new Date().getFullYear())} to get the current year. One can embed Javascript objects with JSX also.

Below you will find my footer.module.css also included, I have changed some of the styles, they were using id in my wordpress blog and I have changed them to use class.

Now let’s try to edit our index.js file and include the footer in there also, when we try to just add the footer below Header tag we will see an error. Adjacent JSX elements must be wrapped in an enclosing tag.

In order to mitigate the error we need to add empty tag <> and < / > which makes it pretty ugly, I think a better design will be to use a layout, so in the next section we will talk about how to use Layout and add our content and sidebar. See I told you we will get back to content and sidebar, just a bit later 🙂

Below you will find the fixed index.js file and also the screen shot of what we have so far, still far from done but at least we are getting there.

header-footer-gatsby

header-footer-gatsby

Summary

We created our footer style by using the css module, our styling still requires some more work padding etc but we are slowly progressing and getting there. We will tackle the layout in our next section to make thing clean such that we can use the layout for about, contact etc pages and not repeat the tags everywhere.

WordpresstoGatsby

When it comes to styling in Gatsby, it allows one to style with css, less, scss, etc. I wanted to keep things simple for the time being and will use css and just copy what I have for the header in my blog to see how it will look like in Gatsby. It will be a way to find out the amount of work it will require for me to just create the header layout of my blog.

Getting started

Let’s choose a clean template of Gatsby without any pages etc. Gatsby provides us with the hello-world template which is the minimal template. We will start the template by executing the command below.

Gatsby provides us with a way to create global styling by adding the style reference file into gatsby-broswer.js. Lets create a global.css file and add the html and body css styles. We will create a folder in src/styles and also create a file called global.css inside of it.

Your folder will look like below in vscode.

gatsby-styles-global

gatsby-styles-global

Below is the content of global.css, I copied the html and body styles into this file from my blog.

Now we will need to add gatsby-browser.js file so that it can apply this style globally to our site. The file resides on the root folder where you will also find gatsby-config.js

We also need to edit the file to tell it where our global.css file is residing.

Now we will have the global style that we have applied to our site.

Gatsby component module styling

Gatsby allows us to use css modules out of the box. We will be using css modules for our header, we will create a header.js file inside of the src/components folder.

I will now copy and paste my header source into the header.js file. Below I have replaced with Link and I am also passing in a prop into my function, so that I can use the data that will be passed in. I have also replaced the css class to use className rather.

As you can see there are a lot of css elements here and wordpress generates a lot of stuff by default. Not necessary clean html I guess.

Now let’s create our style for our header.js file, we will create a file called header.module.css inside the components folder.

Now we need to modify our header.js file to use these css styles. By default I am using kebab-case for my css, and in our javacript code I can refer to the style by camel casing e.g main-nav becomes mainNav.

Below you will see the clean version of the header.js file where I imported the style and used it in the component.

You may see something funky above where I use join for two styles. In React you need to use an array and join it with two styles in order for it to have two styles in one component. One of the nice thing about using modules is that all the css styles will be unique to the site, so no conflict at all. e.g headerStyles.logoDefault will be converted by Gatsby to header-module–logo-default–1YbkP.

Launching the site

Finally we need to modify our src/pages/index.js and use our Header file inside of it. We will also pass in 2 properties into Header, the title and tagline of our blog.

Finally lets launch the develop server and view how it looks like.

headerpage-from-gatsby

headerpage-from-gatsby

Summary

We covered styling using global styles and also how to use components modules css to style a component. How Gatsby will auto generate css unique code so that there are no conflicts between other components and styles. I hope you see that by default your code will be quite clean by gatsby. Next up we will try to cover more the body and footer for the blog.

UA-4524639-2