Github Copilot Coding With Copilot
Github Copilot Coding With Copilot
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.
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.
5
Table of Contents:
6
1
Introduction to GitHub
Copilot
Overview
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.
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.
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.
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.
Overview
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.
The GitHub Copilot extension has been successfully installed in my visual studio.
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.
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; }
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
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 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.
}
We have above all code with suggestions only.
Let’s move forward. It will suggest a method to get all blogs.
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.
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 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
}
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.
We will create an encryption method with key and values, so I will write comment accordingly.
As an example, I will now proceed to create an additional helper method to convert an enum to a
string.
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.
Overview
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.
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.
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