100% found this document useful (2 votes)
2K views

Github Copilot Coding With Copilot

Uploaded by

hsgnfgkid
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
2K views

Github Copilot Coding With Copilot

Uploaded by

hsgnfgkid
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

GitHub Copilot - Coding with Copilot

YOU’RE AI PAIR FOR WRITING CODE

Md RIJWAN ALAM ANSARI AND SATYADEVI KARKI

All rights reserved. No part of this publication may be reproduced, distributed or transmitted in any
form or by any means, including photocopying, recording, or other electronic or mechanical
methods, without the prior written permission of the publisher, except in the case of brief quotations
embodied in critical reviews and certain other noncommercial uses permitted by copyright law.
Although the author/co-author and publisher have made every effort to ensure that the information
in this book was correct at press time, the author/co-author and publisher do not assume and
hereby disclaim any liability to any party for any loss, damage, or disruption caused by errors or
omissions, whether such errors or omissions result from negligence, accident, or any other cause.
The resources in this book are provided for informational purposes only and should not be used to
replace the specialized training and professional judgment of a health care or mental health care
professional. Neither the author/co-author nor the publisher can be held responsible for the use of
the information provided within this book. Please always consult a trained professional before
making any decision regarding the treatment of yourself or others.

Author/Co-Author – Md Rijwan Alam Ansari, Satyadevi Karki


Publisher – C# Corner
Editorial Team – Archie Vankar, Deepak Tewatia
Publishing Team – Praveen Kumar, Amit Kumar
Promotional & Media – Rohit Tomar, Rohit Sharma

2
Author Bio
Md Rijwan Alam Ansari is an experienced software architect and technology enthusiast with a strong
passion for empowering fellow developers and sharing knowledge. With a passion for leveraging
cutting-edge technologies to streamline the development process, they have dedicated themselves
to exploring the potential of AI-assisted programming. With a comprehensive understanding of
various programming languages, frameworks, and tools, Rijwan has successfully designed and
implemented mid to large scale solutions. His expertise in software architecture enables him to create
scalable and efficient systems that meet the needs of modern businesses.

Furthermore, Rijwan Ansari is a Microsoft MVP (Most Valuable Professional), Microsoft certified
trainer, C# Corner MVP, Certified Scrum Master, CSPO and with 15+ Microsoft certifications in
developer technologies.

In addition to his technical skills, Rijwan has a strong commitment to knowledge dissemination. He
actively contributes to the developer community through blogging, sharing insights, best practices,
and tutorials. By addressing common challenges and emerging trends, he aims to equip fellow
developers with the tools and knowledge necessary to succeed.

With a passion for community engagement, Rijwan frequently speaks at conferences, meetups, and
workshops, sharing their expertise and insights with fellow developers. He is known for their dynamic
and engaging presentation style, inspiring and motivating others on their software development
journey.

As a technology enthusiast, Rijwan stays up to date with the latest advancements in the industry.
He thrives on exploring emerging technologies and experimenting with new tools to expand his
expertise. Likewise, he takes pleasure in helping others acquire new skills and expand their
technical knowledge. His commitment to education and mentorship has positively impacted
countless aspiring developers, guiding them towards success in their own careers.

3
Co-Author Bio
Satyadevi Karki is a highly accomplished Blockchain Developer, Sr. Software Engineer, Microsoft
MVP, C# Corner MVP, Microsoft Certified Trainer, MCP, and MCTS with over 12 plus years of
invaluable professional experience in the realm of Microsoft Technologies and Software
Development. With that she has nearly 20 Microsoft certifications in developer technologies. Her
journey in the tech world began over a decade ago, and since then, she has been at the forefront of
cutting-edge technologies.

Moreover, Satya's expertise goes beyond traditional development, as she has delved deep into the
world of emerging cutting -edge technologies. Her proficiency spans across a wide array of domains,
including Azure Cognitive Services, Azure Services, Artificial Intelligence, Machine Learning,
Software Architecture, SharePoint Technologies, SharePoint Apps, Cloud Apps, Power BI, Power
Apps, Power Automation, C#, C#.NET, VB.NET, .NET Reporting Services, Web Design, and
Development, Blockchain, DApps, DeFi, Smart Contract, NFTs.

Embracing her love for sharing knowledge, Satya enjoys contributing to tech communities by writing
articles, sharing videos, speaking at events and conferences as well as frequently contributing to the
open-source community. Her drive to stay ahead in the fast-paced world of technology motivates her
to continually learn, master new cutting-edge technologies and help others.

As a community contributor, Satya Karki's dedication to her craft and her unwavering commitment to
sharing knowledge make her a true luminary in the tech industry. Her contributions have not only
enriched the development community but have also inspired countless aspiring technologists to
pursue their passions and excel in their careers.

Additionally, Satya's blog, RIJSAT.COM, is an extensive treasure trove for developers and data
engineers seeking valuable resources. On this platform, visitors can access a wealth of articles,
courses, news, videos, and issue resolutions, all carefully curated by Satya and team.

4
Acknowledgement

I would like to express my deepest gratitude to my wife, Satyadevi Karki, who not only motivated
me to write this book, but also collaborated with me as a co-author. She has been my constant
source of support, encouragement, and wisdom throughout this journey. Without her, this book
would not have been possible.

Moreover, I would like to convey my heartfelt appreciation to Mr. Mahesh Chand for urging me to
write this book. He was the one who initially proposed that I share write up with the world, and he
and C# Corner Team assisted me throughout the process of editing and publishing.

Furthermore, I am grateful to Mr. Lahiru Munindradasa for motivating me to delve deeper into the
subject matter.

Lastly, I would like to thank my family, friends and C# Corner team for their unwavering support and
love. They always believed in me and cheered me on.

— Md Rijwan Alam Ansari

5
Table of Contents:

Chapter 1 - Introduction to GitHub Copilot ......................................................................................... 7


Background................................................................................................................................... 8
What is GitHub Copilot? ................................................................................................................ 8
Key Features and Capabilities of GitHub Copilot........................................................................... 9
Chapter 2 - Getting Started with GitHub Copilot ............................................................................... 11
Setting up Copilot in your Development Environment ................................................................. 12
Chapter 3 - GitHub Copilot for Visual Studio ..................................................................................... 13
Prerequisites ............................................................................................................................... 14
Using GitHub Copilot for writing code with examples .................................................................. 18
Chapter 4 - GitHub Copilot for Visual Studio Code ............................................................................. 35
Conclusion ..................................................................................................................................... 40

6
1
Introduction to GitHub
Copilot

Overview

In this chapter, we will offer a comprehensive overview of the


innovative tool developed by GitHub in collaboration with OpenAI. It
helps write code faster, giving real-time suggestions and auto-
completions in your preferred code editor. Boosting productivity, it's
a game-changer for developers.

7
Background
We are in the era of Artificial Intelligence, and it is taking over numerous manual and repetitive
tasks. We have AI in almost every system, tool, or device, regardless of any domain. Likewise, we
are surrounded by AI and its applications. AI is reducing our workloads, recommending the best
options, doing things faster, and many more. Now we have ample use cases of AI in every product
and service. Importantly, every tech company is exploring AI and implementing its application in its
solutions to enhance user experience.
Likewise, AI can be implemented in IT to automate repetitive tasks, resolve support issues, reply to
IT requests, provide IT support and assistance, etc. Most importantly, AI can play a vital role in
designing solutions, writing code, finding issues in code, fixing bugs, QA, optimizing code and
performance, and can be our copilot in development.
Yes, AI can be our copilot in software development. In fact, AI can be our copilot in every phase of
development, starting from building, testing, deploying, managing, and updating. This is where
GitHub Copilot comes in.
GitHub Copilot is a new AI tool that helps developers to write code faster and better. Indeed, it is an
AI coding partner that provides suggestions to your code and can write code based on the
description in natural language. This AI copilot model is built on a heavy GitHub code base and
OpenAI collaboration, which is further backed by Microsoft.

What is GitHub Copilot?


In the realm of software development, automation and artificial intelligence have brought about
significant transformations. GitHub Copilot is a tool that uses artificial intelligence to assist
developers in suggesting and writing code based on the context and the tool was first announced
by GitHub on 29th June 2021.
GitHub Copilot is powered by OpenAI Codex, a generative pretrained language model created by
OpenAI. It is developed with the collaboration of OpenAI and Microsoft and uses OpenAI’s Codex
language model, which has been trained on a massive dataset of public code repositories. GitHub
Copilot can suggest code completions, functions, and even entire programs, based on the context
of the code that you are currently writing through natural language. Furthermore, it can provide
suggestions to optimize the code performance, identify bugs and provide fixes of it, and generate
documentation of the code.
Additionally, GitHub Copilot can also be used with several programming languages, including
Python, JavaScript, Java, C++, and Go. It can also be helpful to generate code for a variety of
tasks, such as web development, data science, and machine learning.
Moreover, it can be directly integrated well with a variety of Integrated Development Environments
(IDEs), like Visual Studio, Visual Studio Code, Neovim, and JetBrains IDEs.
When you use GitHub Copilot, it analyzes the code you have already written and suggests
additional lines of code that it thinks you might want to add. These recommendations are based on
Codex's understanding of the code you have written, as well as its knowledge of the programming
language you are using. You can accept or reject Copilot's suggestions, and you can also edit them

Introduction to GitHub Copilot 8


to fit your needs. By automating the process of writing code, Copilot can free up developers to
focus on more creative and strategic tasks.

Key Features and Capabilities of GitHub Copilot


GitHub Copilot boasts a range of potential features and capabilities that make it a game-changer in
the world of AI-assisted programming. Let us explore some of its key functionalities:

Intelligent Code Completion:


GitHub Copilot offers intelligent code completion that goes beyond basic suggestions. It analyzes
the context of your code in real-time and generates relevant code snippets, completing repetitive or
boilerplate sections effortlessly. Whether it is completing function calls, variable declarations, or
entire code blocks, Copilot provides accurate and context-aware suggestions.

Contextual Understanding:
One of Copilot's standout capabilities is its ability to understand the context of your code. It gains
knowledge from existing code patterns and can provide suggestions that align with the required
behavior or functionality you are aiming to achieve. This contextual understanding allows Copilot to
generate code that fits seamlessly within your project, saving you time and effort.

Language Support:
GitHub Copilot supports a variety of programming languages, allowing developers to use their
preferred languages seamlessly. It covers popular languages like Python, C#, JavaScript, C++, and
Java as well as more specialized ones like Go, TypeScript, and Ruby. This wide language coverage
makes Copilot available to developers across various domains.

Code Generation and Exploration:


GitHub Copilot is great at generating code snippets, functions, and even entire classes based on a
given context or task. It can help you explore different code options by offering alternative
implementations or suggesting improvements to your existing code. This functionality allows you to
experiment with different approaches and learn new programming techniques.

Compatibility with Popular Tools and Editors:


GitHub Copilot integrates seamlessly with popular code editors and integrated development
environments (IDEs), making it accessible to a wide range of developers. Whether you prefer Visual
Studio, Visual Studio Code, JetBrains IDEs, Neovim, or any other supported editor, you can
leverage Copilot's capabilities directly within your preferred development environment.

Support for Code Documentation:


Copilot is a tool that helps you document your code with ease. It can generate comments and
docstrings that explain the functionality of your functions, classes, and variables, based on their
names and context. This way, you can avoid writing documentation manually and maintain a
consistent style throughout your codebase.

Introduction to GitHub Copilot 9


Accessibility and Availability:
GitHub Copilot is designed to be accessible to developers of all skill levels. Whether you're a
seasoned programmer or just starting your coding journey, Copilot can assist you by reducing the
cognitive load associated with writing code. It's available as a plugin or extension for popular code
editors, allowing developers to easily integrate it into their workflow.

Continuous Improvement:
GitHub Copilot is continually learning and evolving. OpenAI and GitHub actively gather feedback
from users to improve Copilot's accuracy, refine its suggestions, and expand its capabilities. The
collaborative nature of its development ensures that Copilot gets better over time, benefiting from
the collective knowledge and experiences of the developer community.
GitHub Copilot has the potential to revolutionize the way developers write code. Its intelligent code
completion, contextual understanding, and support for multiple languages empower developers to
write code faster, explore new possibilities, and focus on higher-level problem-solving. As Copilot
continues to evolve, it promises to be an invaluable tool for developers, boosting productivity and
efficiency in software development projects.

Introduction to GitHub Copilot 10


2
Getting Started with GitHub
Copilot

Overview

This chapter guides you through the initial setup process, helping
you install and configure Copilot in your development environment.
You will become familiar with Copilot's user interface, learning how
to navigate its features and interact with its suggestions effectively.

11
Setting up Copilot in your Development Environment
1. Sign into a GitHub Account
GitHub Copilot requires authentication with your GitHub account to function properly. Make sure
you are signed into your GitHub account within your code editor. If you don't have a GitHub
account, create one at github.com.
2. GitHub Copilot Subscription
GitHub Copilot is paid subscription which comes with two pricing models: Individuals and
Organizations. However, it is free for the teachers, authentic students, and maintainers of
popular open-source projects. You can start with a one-time 30-day trial if you don’t have any
subscriptions.
You can go to this https://github.com/github-copilot/business_signup/choose_business_type link
and choose organization of your type.

3. Code Editor IDE


GitHub Copilot integrates seamlessly with popular code editors and IDEs. Make sure you have
one of the supported editors installed on your system. GitHub Copilot is an extension tool that is
available for Visual Studio, Visual Studio Code, JetBrains suite of IDEs, and Neovim. Therefore,
you need to have one of these IDEs to use the GitHub Copilot extension.
In this book, we will use the Copilot extension in Visual Studio and Visual Studio Code.

Getting Started with GitHub Copilot 12


3
GitHub Copilot for Visual
Studio

Overview

Learn how Copilot, the AI coding assistant, seamlessly integrates


into Visual Studio, offering instant code suggestions and
completions. Supercharge your coding in Visual Studio with this
teamwork of GitHub and OpenAI.

13
GitHub Copilot can be seamlessly integrated into various IDEs, providing its powerful code
generation capabilities. In this section, we will explore how to integrate Copilot into Visual Studio
and utilize it to generate sample code based on the context.

Prerequisites

- We need to have GitHub Account and GitHub Copilot subscription as mentioned above
section point 1 and 2.
- Visual Studio 2022 version 17.4.4 or later.
Please note that as of now, GitHub Copilot is not available for Visual Studio for Mac.
In this section, we will explore how to integrate Copilot into Visual Studio and utilize it to generate
sample code based on the context.
To begin, open Visual Studio, Select Extension Tab and click Manage Extensions as portrayed.

We will then search for the GitHub Copilot extension as shown below.

GitHub Copilot for Visual Studio 14


We will download the extension, GitHub Copilot.

GitHub Copilot for Visual Studio 15


As per instructions, we will close the Visual Studio to install the extension, Copilot.

GitHub Copilot for Visual Studio 16


To verify the installation by opening the Visual Studio, go to manage extensions and check the
GitHub Copilot.

The GitHub Copilot extension has been successfully installed in my visual studio.

GitHub Copilot for Visual Studio 17


You will notice a copilot icon on every page as shown below.

After integrating with Visual Studio, Copilot will analyze the context of your code and offer intelligent
suggestions. By simply typing a few characters or invoking the Copilot feature, you can access a
wide range of code snippets and completions generated by Copilot. We will explore in next section.

Using GitHub Copilot for writing code with examples


Let us embark on creating a new project and leverage the capabilities of the AI copilot for code
suggestions. In this example, we will create a simple ASP.NET Core project using the Blazor Server
App Template.
For getting started with Blazor Web Application, check out this article. https://www.c-
sharpcorner.com/article/build-a-web-app-with-blazor-in-net-7/
Now let us implement a use case in the solution using GitHub Copilot. Here, we will an interface to
add a blog detail into database.
Let me create a Blog class and write comment as shown below.

GitHub Copilot for Visual Studio 18


Based on my comment “Create a new class blog with 10 properties”, the GitHub Copilot has
created a complete class with all the necessary properties required for the blog. Furthermore, the
copilot gives to use the code and explore another suggestion.
We can click Tab button and the whole function is ready just by clicking. So we can use Tab to
accept the suggestion, however, we can request for another sample or code with Alt+ as shown
below.

GitHub Copilot for Visual Studio 19


I will pick the first suggestion and click Tab.
However, this code has a warning as shown below.

To overcome the warning, I will modify the comment for validation.

GitHub Copilot for Visual Studio 20


Now I have a blog class with no warning. Additionally, I want to add a constructor, so we will add
comment accordingly.

Here my complete model class.

GitHub Copilot for Visual Studio 21


I have my complete model class with two comments and without writing any code. That’s GitHub
Copilot. Even, we can create above complete class with one comment and add description as
illustrated below.

Code:
public class Blog
{
public int Id { get; set; }
public string Title { get; set; }
public string? Description { get; set; }
public string? Body { get; set; }
public string? TagList { get; set; }
public string? Slug { get; set; }

GitHub Copilot for Visual Studio 22


public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
public bool Favorited { get; set; }
public int FavoritesCount { get; set; }

public Blog(int id, string title, string? description, string? body, string?
tagList, string? slug, DateTime createdAt, DateTime updatedAt, bool favorited, int
favoritesCount)
{
Id = id;
Title = title;
Description = description;
Body = body;
TagList = tagList;
Slug = slug;
CreatedAt = createdAt;
UpdatedAt = updatedAt;
Favorited = favorited;
FavoritesCount = favoritesCount;
}
}

Next, let's proceed with creating a database context class within the Data folder of our project. With
the help of GitHub Copilot, you can accomplish this task swiftly. Simply add a comment indicating
your intention, and Copilot will intelligently generate the complete code for the context class,
tailored to your specific needs. This feature of Copilot significantly reduces the time and effort
required to write the boilerplate code for the database context, allowing us to focus on the essential
aspects of our project.

Here, we can observe that the database context class is suggested specific to my project and
context. It has already included the necessary DbSet based on our model. However, when we

GitHub Copilot for Visual Studio 23


select the suggested code, Visual Studio Code IntelliSense will alert us to any missing packages
that need to be imported for the code to function correctly. This feature ensures that we have all the
required dependencies in place, allowing your code to compile and run smoothly.

Please note that when working with GitHub Copilot, it is important to manually add any required
packages or dependencies. While Copilot provides helpful code suggestions, it does not
automatically add packages to your project. This tool is designed to assist you with generating code
snippets and improving your productivity but does not have the capability to make changes directly
to your project. Therefore, it is your responsibility to add the necessary packages and manage the
project's dependencies to ensure proper functionality.
Therefore, we will add those packages manually as suggested by code IntelliSence of visual
studio.
Let me navigate to the program file to register the application database context.

It will auto-suggest for new service for database context. Let us accept the comment. Furthermore,
the copilot will suggest me the code as shown below.

GitHub Copilot for Visual Studio 24


We will proceed by accepting the suggestion and continue with performing CRUD (Create, Read,
Update, Delete) operations.
Next, we will add a class called BlogServices to our project. Copilot will intelligently suggest the
constructor for the class, including a private variable for the MyDbContext. This will enable us to
establish a connection to the database and access the necessary functionalities within our
BlogServices class. By accepting Copilot's suggestions, we can quickly set up the initial structure
of the class and proceed with implementing the desired business logic for our blog-related
operations.

GitHub Copilot will provide suggestions for the constructor. Copilot's intelligent code generation
capabilities will automatically propose a constructor template that includes the necessary
parameters and initialization logic.

GitHub Copilot for Visual Studio 25


Code:
namespace SampleGitHubCopilot.Data
{
//create a new class MyDbContext for entity framework
public class MyDbContext : DbContext
{
//create a new constructor for MyDbContext
public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
{
}

//create a new property for Blog


public DbSet<Blog> Blogs { get; set; }
}

}
We have above all code with suggestions only.
Let’s move forward. It will suggest a method to get all blogs.

GitHub Copilot for Visual Studio 26


Moving forward, as we continue developing the BlogServices class, GitHub Copilot will offer
suggestions for implementing the method to retrieve all blogs. Copilot's advanced code generation
capabilities will provide a template for the GetAllBlogs() method.

By accepting Copilot's suggestion, we can quickly incorporate the logic for fetching all blogs and
proceed with further enhancements or modifications as needed.

Continuing with the development of the BlogServices class, we will accept GitHub Copilot's
suggestions for other operations such as updating, creating, and deleting blogs.

GitHub’s intelligent code generation will provide the comment as well as the methods for CRUD
operations as shown below.

GitHub Copilot for Visual Studio 27


Furthermore, GitHub Copilot can assist us in adding null validation by simply updating a comment.
By indicating the need for null validation within the comment, Copilot's intelligent suggestions will
provide code modifications to handle potential null values appropriately.

Similarly, when implementing the add operation within the BlogServices class, GitHub Copilot will
provide suggestions for both the comment and the corresponding code.

GitHub Copilot for Visual Studio 28


You may observe that the comment generated by GitHub Copilot is contextually derived. As an
example, it considers your previous comment and suggests incorporating validation based on that
context. This intelligent behavior of Copilot allows it to understand the flow of your code and provide
more relevant and tailored suggestions.

GitHub Copilot has been instrumental in coding my entire class and its methods. With its AI-
powered assistance, Copilot has generated the necessary code based on the provided context and
suggestions.
The complete code for the class is shown below.
public class BlogServices
{
//create a constructor for MyDbContext

GitHub Copilot for Visual Studio 29


private readonly MyDbContext _context;
public BlogServices(MyDbContext context)
{
_context = context;
}

//create a method to get all blogs


public async Task<List<Blog>> GetAllBlogs()
{
return await _context.Blogs.ToListAsync();
}

//create a method to get a blog by id with null validation


public async Task<Blog> GetBlogById(int? id)
{
if (id == null)
{
return null;
}
return await _context.Blogs.FirstOrDefaultAsync(b => b.Id == id);
}

//create a method to add a blog with validation


public async Task<bool> AddBlog(Blog blog)
{
if (blog == null)
{
return false;
}
_context.Blogs.Add(blog);
await _context.SaveChangesAsync();
return true;
}

//create a method to update a blog with validation


public async Task<bool> UpdateBlog(Blog blog)
{
if (blog == null)
{
return false;
}
_context.Blogs.Update(blog);
await _context.SaveChangesAsync();
return true;
}

}
The code snippet above is just one example of how we can use GitHub Copilot to generate code
from comments and descriptions. However, the tool will suggest some alternatives and you can
select based on your situation. We can also write code for logging, model validation, data type
conversion, and more. In this article, we will show how to create some helper methods using GitHub
Copilot and explore its features. To start, let's create a helper class in the Service folder and add a
comment as follows.

GitHub Copilot for Visual Studio 30


We can select the suggested constructor with logger.

We will create an encryption method with key and values, so I will write comment accordingly.

GitHub Copilot for Visual Studio 31


Code:
// create a encryption function with key and value
public string Encrypt(string key, string value)
{
try
{
//create a new instance of AesManaged
using (var aes = new AesManaged())
{
//set the key
aes.Key = Encoding.UTF8.GetBytes(key);
//set the initialization vector
aes.IV = Encoding.UTF8.GetBytes(key);
//create a new instance of MemoryStream
using (var memoryStream = new MemoryStream())
{
//create a new instance of CryptoStream
using (var cryptoStream = new CryptoStream(memoryStream,
aes.CreateEncryptor(), CryptoStreamMode.Write))
{
//create a new instance of StreamWriter
using (var streamWriter = new StreamWriter(cryptoStream))
{
//write the value to the stream
streamWriter.Write(value);
}
//return the encrypted data
return Convert.ToBase64String(memoryStream.ToArray());
}
}
}
}
catch (Exception ex)
{
//log the error
_logger.LogError(ex, "Error encrypting value");
//return null
return null;
}
}
Even, you can use Alt+ to explore different suggestions and tab to select based on your interest and
requirement. Let me select the suggested option. If you notice, it suggests the log of exception
based on my class constructor. Meaning, the copilot is proposing the code based my class and
project context.

GitHub Copilot for Visual Studio 32


It knows the context and recommends decryption methods as shown.

As an example, I will now proceed to create an additional helper method to convert an enum to a
string.

GitHub Copilot for Visual Studio 33


Code:
// create a function to convert enum to string with validation
public string EnumToString<T>(T value)
{
//check if the value is null
if (value == null)
{
//return null
return null;
}
//return the string value of the enum
return value.ToString();
}

One of the benefits of using the AI pair programmer, copilot, is that it can generate code for our
applications based on our comments. For example, in the above snippet, I did not write any code
myself. I just described what I wanted to do in clear and concise comments. Then, copilot
suggested the code that matched my intention. By considering the context, Copilot helps ensure
that the generated code aligns with your specific requirements and promotes best practices. This
contextual awareness enhances the overall efficiency and effectiveness of Copilot, enabling you to
produce code that meets your needs while adhering to established coding standards.
This collaborative partnership between myself and Copilot has significantly expedited the
development process, allowing me to focus on higher-level aspects of the project while Copilot
handles the implementation details. Leveraging the capabilities of Copilot has not only saved time
and effort but also ensured the accuracy and consistency of the generated code. It is truly an
invaluable AI partner in the development journey, empowering me to achieve efficient and high-
quality coding results.

GitHub Copilot for Visual Studio 34


4
GitHub Copilot for Visual
Studio Code

Overview

This chapter helps write code faster by giving suggestions and


completions in real-time. Elevate coding efficiency with this powerful
collaboration between GitHub and OpenAI.

35
Visual Studio Code has become one of the favorite code editors for most of the developers because
of its versatility, speed, and features. It supports a wide range of programming languages, extensions,
and integrations with other tools.
As mentioned in section “Setting up GitHub Copilot in you Development Environment”, we need to
follow preliminary the steps to set up GitHub Copilot in Visual Studio Code.
1. Sign for GitHub Account
2. Active GitHub Copilot Subscription
3. Visual Studio Code is installed in your development environment.
We will commence with the installation of GitHub Copilot for Visual Studio code.
Open Visual Studio Code on your computer.
Locate and click on the Extensions tab, which is represented by a square icon on the left sidebar of
the Visual Studio Code interface as depicted below.

In the search bar at the top of the Extensions view, type "GitHub Copilot" and press Enter. The
search results will display the GitHub Copilot extension. Click on the "Install" button next to the
extension.

GitHub Copilot for Visual Studio Code 36


Sign in with your GitHub account and authorize Visual Studio Code for GitHub Copilot.

GitHub Copilot for Visual Studio Code 37


When you will click to Sign in with GitHub option then you will be redirected to the browser to
authorize with login.

GitHub Copilot for Visual Studio Code 38


Start coding and enjoy the suggestions from GitHub Copilot!
You will notice GitHub Copilot icon in task bar.

With GitHub Copilot installed, you are now ready to take advantage of its powerful code generation
and suggestion capabilities within Visual Studio Code. Enjoy the enhanced coding experience and
increased productivity that Copilot brings to your development workflow.
Throughout this guide, we explored the process of installing GitHub Copilot as an extension in Visual
Studio Code. Once installed, Copilot seamlessly integrates into the IDE, providing real-time code
suggestions based on the context of your code.
We can use GitHub Copilot to write the code as shown in section Visual Studio with examples.

GitHub Copilot for Visual Studio Code 39


Conclusion
In this book, we explored the fascinating world of GitHub Copilot, an AI-powered coding assistant that
revolutionizes the way developers write code. We then delved into the core features and capabilities
of GitHub Copilot, including its intelligent code completion, code generation, and code documentation
support. We learned how Copilot can significantly speed up coding tasks, provide context-aware
suggestions, and assist in generating boilerplate code, thereby boosting developer productivity and
efficiency.
The book also provided a step-by-step guide on getting started with GitHub Copilot, covering the
initial setup process, integration with popular code editors (Visual Studio Code and Visual Studio),
and configuring Copilot to align with your coding preferences.
By following the guidance and best practices provided in this book, you are equipped with the
knowledge and skills to effectively utilize GitHub Copilot in your coding journey. Whether you are a
beginner or an experienced developer, Copilot can become your invaluable coding partner, helping
you write code faster, reduce repetitive tasks, and unlock new levels of productivity.
Furthermore, we successfully implemented a use case using GitHub Copilot, showcasing its
remarkable capabilities. With the assistance of Copilot, we were able to perform the entire CRUD
(Create, Read, Update, and Delete) operations along with helper methods. It is worth noting that we
accomplished this without manually writing extensive amounts of code. By relying on the code
suggestions provided by GitHub Copilot, we streamlined the development process and avoided the
need to write code from scratch.
In conclusion, this book has provided a comprehensive overview of GitHub Copilot, empowering you
to leverage its capabilities to enhance your coding experience, boost productivity, and embrace the
benefits of AI-assisted programming. Embrace GitHub Copilot as your coding companion and embark
on a journey of faster, more efficient, and more enjoyable software development.

40
OUR MISSION
Free Education is Our Basic Need! Our mission is to empower millions of developers worldwide by
providing the latest unbiased news, advice, and tools for learning, sharing, and career growth. We’re
passionate about nurturing the next young generation and help them not only to become great
programmers, but also exceptional human beings.

ABOUT US
CSharp Inc, headquartered in Philadelphia, PA, is an online global community of software
developers. C# Corner served 29.4 million visitors in year 2022. We publish the latest news and articles
on cutting-edge software development topics. Developers share their knowledge and connect via
content, forums, and chapters. Thousands of members benefit from our monthly events, webinars,
and conferences. All conferences are managed under Global Tech Conferences, a CSharp
Inc sister company. We also provide tools for career growth such as career advice, resume writing,
training, certifications, books and white-papers, and videos. We also connect developers with their poten-
tial employers via our Job board. Visit C# Corner

MORE BOOKS

You might also like