Copilot Handbook For Students and Developers
Copilot Handbook For Students and Developers
Author
Mahesh Chand
And Copilot, ChatGPT, and Gemini
1
Copyright 2024 Mahesh Chand and CSharp Inc.
Table of Contents
2
Copyright 2024 Mahesh Chand and CSharp Inc.
CHAPTER 4 DOCUMENATION USING COPILOT ........................................................................... 29
Commenting code using Copilot................................................................................. 29
Documentation using Copilot ...................................................................................... 34
CHAPTER 5 CODE REFACTORING .............................................................................................. 38
Refactor a code block ................................................................................................ 38
Refactor a program or application ........................................................................... 41
Update code to new version...................................................................................... 41
CHAPTER 6 WRITE TEST CASES USING COPILOT ........................................................................ 42
CHAPTER 7 FIX ERRORS USING COPILOT ................................................................................... 44
Code Review. Again! ....................................................................................................... 49
CHAPER 8 COPILOT SLASH COMMANDS .................................................................................... 52
What are Copilot slash commands? .......................................................................... 52
Slash commands explained ......................................................................................... 53
/generate: Generate code to answer your question........................................... 53
/explain: Explain the selected code. ...................................................................... 53
/doc: Add a documentation comment. .................................................................. 55
/fix: Propose a fix for problems in the selected code. ...................................... 56
/tests: Create unit tests for the selected code. ................................................. 56
/optimize: Improve code performance ..................................................................... 57
Reference: scope Copilot results to a particular file or entire solution .......... 58
CHAPTER 9 CODE CONVERSION ................................................................................................ 60
SUMMARY ................................................................................................................................ 62
3
Copyright 2024 Mahesh Chand and CSharp Inc.
ABOUT THE AUTHOR
Mahesh Chand is a distinguished
figure in the software development
and technology industry, with over 25
years of experience as an award-
winning Software Architect and
Author. He has built a reputation for
creating innovative software
solutions using cutting-edge
technologies.
As a serial entrepreneur, Mahesh has
founded several successful
companies, including CSharp Inc. and
Mindcracker. He is also the founder
of C# Corner, a leading online
community for software developers that boasts 29.4 million annual visitors
and 3 million registered members.
His contributions to the tech industry have earned him notable recognition,
including being a former Microsoft Regional Director and a 14-time Microsoft
MVP (Most Valuable Professional). Recently, he was inducted into the Forbes
Business Council.
In addition to his entrepreneurial ventures, Mahesh is an accomplished author
of several programming books and an international keynote speaker. He
continues to shape the tech industry through his leadership roles in various
initiatives, including CSharpTV, Web3Universe, BCrypt, and HackIndia.
Mahesh actively contributes to developer education and growth through his
platforms and speaking engagements. His commitment to sharing knowledge
and fostering innovation has solidified his position as a prominent figure in the
software development community.
Mahesh Chand
Founder C# Corner
4
Copyright 2024 Mahesh Chand and CSharp Inc.
CHAPTER 1
INTRODUCTION
Welcome to ‘COPILOT HANDBOOK for students and developers,’ a book
published by [Link]. Copilot serves as the trusted companion for
computer science students, programmers, developers, QA and test engineers,
and technical writers.
If you’re using one or more of the Microsoft products such as Windows PC,
Windows Operating System, Office 365, Azure, Visual Studio, or Edge, you will
see Copilot almost everywhere.
There are two Copilots – Microsoft Copilot and Github Copilot. Microsoft
Copilot is a general Copilot and is available through various Microsoft products,
including Windows, Bing, Edge, Office 365, Teams, Power Platform, and Azure.
Github Copilot is specifically designed for programmers and developers who
actively write and maintain software code. This book focuses on Github
Copilot.
In this book, you’ll learn the fundamentals of Github Copilot and discover how
to leverage its various features to enhance productivity, efficiency, and code
quality using Copilot and Visual Studio. By the time you finish reading and
practicing this book, you should be able to boost your productivity and the
quality of the code you write.
5
Copyright 2024 Mahesh Chand and CSharp Inc.
• It focuses primarily on enhancing the coding experience by suggesting
code snippets, functions, and even entire classes based on the context
of the code being written.
Microsoft Copilot
Generally, refers to a suite of AI tools integrated into Microsoft products,
aimed at enhancing productivity across various applications.
• Microsoft Copilot is available as a part of Windows operating system
and can be accessed from the Windows Task Bar.
• Microsoft Copilot is also available in various Microsoft products like
Office (Word, Excel, and PowerPoint), Edge browser, Teams, Power
Platform, and Azure.
• In these applications, Copilot assists by generating text, creating
summaries, suggesting formulas, designing slides, and more.
• It leverages AI to help users perform tasks more efficiently across
different Microsoft software products.
6
Copyright 2024 Mahesh Chand and CSharp Inc.
Github Copilot was also able to increase the performance of development and
hence delivery by 55%.
7
Copyright 2024 Mahesh Chand and CSharp Inc.
GitHub Copilot is available:
• In your IDE
• In GitHub Mobile, as a chat interface
• On the command line, through the GitHub CLI
• On [Link], with a subscription to Copilot Enterprise
8
Copyright 2024 Mahesh Chand and CSharp Inc.
this screen, you can buy a new or review your existing subscription.
On this screen, you can also set up your subscription policies and more
settings.
9
Copyright 2024 Mahesh Chand and CSharp Inc.
What programming language does Copilot support?
Copilot supports major popular programming languages, including Python,
JavaScript/TypeScript, Ruby, Go, Java, PHP, C++, C, C#, Rust, and Swift.
Copilot also supports front-end framework such as [Link] Core, React, and
Angular.
Is Copilot free?
While GitHub Copilot offers a paid tier with monthly or yearly subscriptions,
there are ways to access it for free! Let's break down your options:
Free access for students: Verified students, teachers, and maintainers of
popular open-source projects on GitHub can use Copilot Individual entirely
free. For a student or teacher account, you must verify with your college email
with proof.
Free trial: If you don't qualify for free access, you can still test out Copilot
Individual with a 30-day free trial. After the trial, a paid subscription is
required to keep using it.
Paid subscriptions: For individuals or organizations who don't qualify for free
access or the trial, Copilot offers paid subscriptions. You can manage these
10
Copyright 2024 Mahesh Chand and CSharp Inc.
subscriptions through your personal account (Copilot Individual) or a central
organization account (Copilot Business).
CoPilot licensing
Github Copilot offers three types of licenses, Individual, Business, and
Enterprise. The following table summarizes the difference between these three
types of licenses:
11
Copyright 2024 Mahesh Chand and CSharp Inc.
How does GitHub Copilot work?
GitHub Copilot developed by Microsoft uses LLMs trained by OpenAI on vast
amount of open-source code including millions of code repositories from
Github, Microsoft, and online communities.
Copilot uses machine learning to predict and suggest code based on the
context of what the developer is currently writing.
Copilot can also learn from your local project in your IDE and suggest code
based on the project’s style and
12
Copyright 2024 Mahesh Chand and CSharp Inc.
Is GitHub Copilot safe to use with proprietary or
sensitive code?
GitHub Copilot is designed to prioritize user privacy and security. However, you
should be cautious when using it with proprietary or sensitive code and always
review suggestions for potential security risks.
If you are building a product that may be sold to others, you may want to be
careful with the code generated by Copilot. While you can generate the code
bit, I recommend you understand it, learn from it, and rewrite your own code.
13
Copyright 2024 Mahesh Chand and CSharp Inc.
Copilot can help you write HTML and CSS code for structuring your web pages
and styling them. For example, you can use Copilot to generate HTML tags,
create divs, add classes, and style elements.
Copilot supports JavaScript and can help you write functions, event handlers,
and other client-side code.
You can use it to create interactive features like form validation, animations,
and dynamic content.
Frameworks and Libraries
Copilot can assist with popular web frameworks and libraries like React,
Angular, and [Link].
It provides code snippets, suggests best practices, and helps you write
components.
Backend Development
While Copilot doesn’t directly handle backend development, it can generate
code snippets for APIs, database connections, and server-side logic.
You’ll need to choose a backend language (such as C#, [Link], Python, or
Java) and implement it separately.
Responsive Design
Copilot can help you create responsive layouts by suggesting media queries
and responsive CSS rules.
Remember to test your website on different devices and screen sizes.
SEO and Accessibility
Copilot can guide you in writing SEO-friendly meta tags, alt attributes for
images, and accessible HTML.
However, understanding SEO and accessibility principles is essential.
Deployment
Copilot won’t deploy your website, but it can assist with code related to
deployment scripts or configuration files.
14
Copyright 2024 Mahesh Chand and CSharp Inc.
2. Copilot code may not be
accurate. CAUTION
Copilot heavily relies on public LLMs
and hence may not be accurate. Prompt Remember that while Copilot is a
engineering is the key to getting the powerful tool, it’s not a substitute for
most out of generative AI assistants like understanding web development
Copilot. Writing effective generative AI concepts. Learning the basics of HTML,
prompts is a key skill you may want to CSS, and JavaScript is crucial for
learn before using Copilot. building a complete and well-
functioning website.
3. Copilot code may not have an Copilot can also make mistakes and
updated version. may use older version of the code. You
Software programming language and need to make sure to review and test
frameworks get updates almost every the code generated by Copilot.
month. The code generated by Copilot
is most likely not the latest version of
the language and framework since
Copilot is usually trained on older data. For example, if C# version 15 is just announced
and you are building your application in this version, Copilot will have no idea of the
new features and obsolete features since it’s probably using an older version of C#
code.
You may want to update your code by yourself to have the latest features in your
program.
Note: Before you can use Github Copilot in Visual Studio, you
must have a Github Copilot license. You can buy
15
Copyright 2024 Mahesh Chand and CSharp Inc.
Launch CoPilot Chat
If you have Visual Studio’s latest version, CoPilot is already integrated in it at
the top right corner of the IDE.
Click on the Open Chat Windows will open Copilot chat where you can start
asking your questions or paste your code for Copilot to review or rewrite.
The first GitHub Copilot screen you will see has the following message:
16
Copyright 2024 Mahesh Chand and CSharp Inc.
I type the following question in the chat window and this is the response I get:
Below this is the complete C# program. At the bottom of the chat window,
there is an option to create a new file and have a Preview.
The Preview windows allow us to Accept the new code in the current file.
17
Copyright 2024 Mahesh Chand and CSharp Inc.
Note: You can also success Copilot in Visual Studio Editor using
Alt + / shortcut or Right click in the Editor and select Ask
Copilot menu option.
18
Copyright 2024 Mahesh Chand and CSharp Inc.
CHAPTER 2
WRITING BOILERPLATE
CODE USING COPILOT
Almost every programmer and developer end up writing boilerplate code, especially at
the beginning of a new project. Copilot is great at generating boilerplate code quickly.
This is actually the most popular use of Copilot to write code for young developers and
students to learn programming.
It will open Copilot chat window where you can ask a question or paste your existing
code.
19
Copyright 2024 Mahesh Chand and CSharp Inc.
Note: If you ask non programming related questions, Copilot
will nicely tell you that it doesn’t support non programming
related questions.
20
Copyright 2024 Mahesh Chand and CSharp Inc.
Hit the Accept button.
This is what my complete program looks like:
using System;
using [Link];
class Program
{
static void Main()
{
string filePath = "path/to/your/[Link]";
int characterCount = 0;
int wordCount = 0;
try
{
using (StreamReader sr = new StreamReader(filePath))
{
string line;
while ((line = [Link]()) != null)
{
characterCount += [Link];
wordCount += [Link](new char[] { ' ', '\t' },
[Link]).Length;
}
}
Listing 1.
I want to read an existing file named [Link]. I update the code with the
following:
string filePath = "C:/temp/[Link]";
21
Copyright 2024 Mahesh Chand and CSharp Inc.
Step 5. Build and run.
Now, build and run the project.
The output looks like the following and displays results on the console:
Code review
Remember, Copilot is your AI programming assistant. You’re still in the driver’s seat.
You must ensure that the code is written by Copilot, follows your standards, quality,
and works the way it is supposed to.
Copilot is also likely to make mistakes since it just writes based on what data it has. It
is your responsibility to do a code review.
Copilot may also use an older version of a programming language or framework. For
example, if the current version of C# is 12.0, Copilot may write code in C# 7.0 or 8.0.
You want to make sure the code is written in the latest version of C#.
I asked Copilot to review the code and update it to C# 12.
22
Copyright 2024 Mahesh Chand and CSharp Inc.
The explanation of the code is below the code:
The Preview option will show the updated code and changes line by line.
23
Copyright 2024 Mahesh Chand and CSharp Inc.
CHAPTER 3
AUTOCOMPLETION
USING COPILOT
Code completion or extending existing code is a common feature Copilot is
used for. Most of the editors are smart enough to auto complete code these
days and suggest code snippet and code blocks as soon as you type
something.
Let’s try this.
I just type File in code editor, you will see the entire line of code is already
there. To accept this suggested code, all I must do is hit TAB.
After I hit TAB key, the next line of the code is already suggested to me.
But I really don’t want to write the above method. But I want to create a
method that reads a text file line by line.
24
Copyright 2024 Mahesh Chand and CSharp Inc.
As soon as I continue the method signature and type ReadLineB.. Copilot
automatically completes my intentions with the method ReadLineByLine as
you can see below.
I hit ENTER below that and the new method suggested by Copilot is the
following:
I hit ENTER again and the next suggested method is the following:
25
Copyright 2024 Mahesh Chand and CSharp Inc.
Extend existing program using Copilot
Now, let’s extend our program. We are going to add a new class in the program
and then add some objects to the text file.
class Author
{
public string Name { get; set; }
public string Email { get; set; }
public string Country { get; set; }
}
26
Copyright 2024 Mahesh Chand and CSharp Inc.
[Link]("Country: ");
string country = [Link]();
Now check the .txt file and you will see the new values are added to the text
file.
27
Copyright 2024 Mahesh Chand and CSharp Inc.
28
Copyright 2024 Mahesh Chand and CSharp Inc.
CHAPTER 4
DOCUMENATION USING
COPILOT
Code commenting and documentation is not something developers enjoy. Code
comments are very useful to make your code readable and maintainable.
Documentation plays a vital role in teams and helps new developers getting
started with the project.
class Program
{
static void Main()
{
// Specify the file path
string filePath = "C:/temp/[Link]";
try
{
// Read the file line by line
using (StreamReader sr = new StreamReader(filePath))
{
string line;
while ((line = [Link]()) != null)
{
// Update character count
characterCount += [Link];
30
Copyright 2024 Mahesh Chand and CSharp Inc.
// Create an instance of the Author class
Author author = new Author
{
Name = name,
Email = email,
Country = country
};
// Method to read the file line by line and display each line
public static void ReadLineByLine(string filePath)
{
using (StreamReader sr = new StreamReader(filePath))
{
string line;
while ((line = [Link]()) != null)
{
[Link](line);
}
}
}
// Method to read all lines from the file and display each line
public static void ReadAllLines(string filePath)
{
string[] lines = [Link](filePath);
foreach (string line in lines)
{
[Link](line);
}
}
Listing 2.
Now only you can comment your existing code but can also ask to remove
existing comments.
The following prompt removes all existing comments from the program.
31
Copyright 2024 Mahesh Chand and CSharp Inc.
Once you accept the changes, all comments from the code will be removed.
You can also add detailed documentation to the program by using the
following prompt.
class Program
{
/// <summary>
/// Entry point of the program.
/// </summary>
static void Main()
{
// Specify the file path
string filePath = "C:/temp/[Link]";
try
{
32
Copyright 2024 Mahesh Chand and CSharp Inc.
// Read the file using a StreamReader
using (StreamReader sr = new StreamReader(filePath))
{
string line;
while ((line = [Link]()) != null)
{
// Update character count
characterCount += [Link];
/// <summary>
/// Reads the file line by line and prints each line to the console.
/// </summary>
/// <param name="filePath">The path of the file to read.</param>
public static void ReadLineByLine(string filePath)
{
33
Copyright 2024 Mahesh Chand and CSharp Inc.
// Read the file using a StreamReader
using (StreamReader sr = new StreamReader(filePath))
{
string line;
while ((line = [Link]()) != null)
{
// Print each line to the console
[Link](line);
}
}
}
/// <summary>
/// Reads all lines from the file and prints each line to the console.
/// </summary>
/// <param name="filePath">The path of the file to read.</param>
public static void ReadAllLines(string filePath)
{
// Read all lines from the file
string[] lines = [Link](filePath);
/// <summary>
/// Adds the author details to the file.
/// </summary>
/// <param name="filePath">The path of the file to write.</param>
/// <param name="author">The author object containing the
details.</param>
public static void AddAuthorToFile(string filePath, Author author)
{
// Write the author details to the file using a StreamWriter
using (StreamWriter sw = new StreamWriter(filePath, true))
{
[Link]($"Name: {[Link]}");
[Link]($"Email: {[Link]}");
[Link]($"Country: {[Link]}");
[Link]();
}
}
}
And this is what I got in the reply for our existing program.
------------------------------------------------------------
Certainly! Here's a detailed blog about the program:
Introduction
35
Copyright 2024 Mahesh Chand and CSharp Inc.
program catches this exception and displays a user-friendly error message
using the [Link] method.
If any other exception occurs during file reading, it is caught by the generic
Exception catch block. The program then displays the error message provided
by the exception using the [Link] property.
Accepting User Input
After reading the file, the program prompts the user to enter author details. It
uses the [Link] method to read the user's input for the name,
email, and country. These inputs are stored in the respective variables name,
email, and country.
Object-Oriented Programming
The program demonstrates object-oriented programming principles by creating
an instance of the Author class. The Author class is defined separately and
contains properties for the author's name, email, and country.
Using the user-provided inputs, the program initializes a new Author object
and assigns the values to its properties.
Writing to File
The program calls the AddAuthorToFile method, passing the filePath and
author objects as arguments. This method appends the author's details to the
end of the file using a StreamWriter object wrapped in a using statement. The
StreamWriter allows us to write text to a file.
Inside the using block, the program writes the author's name, email, and
country to the file using the WriteLine method of the StreamWriter. It also
adds an empty line for better readability.
Additional File Operations
The Program class includes two more helper methods: ReadLineByLine and
ReadAllLines. These methods demonstrate different ways to read the contents
of a file.
The ReadLineByLine method reads the file line by line using a StreamReader
object and displays each line on the console using the [Link]
method.
The ReadAllLines method reads all the lines of the file into an array of strings
using the [Link] method. It then iterates over the array and displays
each line on the console.
Conclusion
In this blog, we explored a C# program that performs file operations, exception
handling, and object-oriented programming concepts. We learned how to read
the contents of a file, handle exceptions, accept user input, create objects,
and write to a file. Understanding these concepts is crucial for building robust
and interactive applications.
----------------------------------
36
Copyright 2024 Mahesh Chand and CSharp Inc.
While the above content may be accurate but make sure you read through it
and change it as needed before publishing it anywhere.
37
Copyright 2024 Mahesh Chand and CSharp Inc.
CHAPTER 5
CODE REFACTORING
Today, many software applications running worldwide are outdated and require
upgrading. Software frameworks, libraries, and programming language versions
evolve approximately every six months to a year. Frequent updates are often
driven by security enhancements and performance optimizations.
To create better software, it’s crucial to keep our code up to date whenever
possible. However, updating code can be time-consuming and resource
intensive. Fortunately, Copilot provides a powerful solution. With Copilot’s
assistance, we can efficiently refactor our code, saving valuable time and
resources.
Code refactoring is the process of rewriting existing code without changing its
external behavior to make it modern, maintainable, readable, fast, and secure.
Refactoring is a key practice in maintaining a healthy codebase, especially in
agile development environments where the codebase frequently evolves.
Here are some common practices involved in refactoring:
• Improving Code Readability: Making the code easier to understand by
renaming variables, breaking large functions into smaller ones, and
adding comments where necessary.
• Reducing Complexity: Simplifying complex logic, for instance by breaking
complex conditions into simpler ones or using design patterns.
• Eliminating Redundant Code: Removing unnecessary or duplicate code
to streamline and optimize performance.
• Enhancing Performance: Optimizing the code to improve performance,
which might involve improving algorithms or data structures.
• Improving Design: Adapting the code to make future changes easier and
safer, often by applying solid design principles.
• Upgrade to the latest versions: Programming languages, frameworks,
and libraries get frequent updates and patches. Code refactoring helps
us to bring new updates in the code and remove obsolete code.
Code refactoring is needed when you suspect some code needs to be updated
or reorganized.
Using Copilot, we can refactor a code block, entire file, or even full application.
38
Copyright 2024 Mahesh Chand and CSharp Inc.
// Create an Author object and add it to the file
Author author = null;
if ([Link] > 0)
{
if ([Link] > 0)
{
if ([Link] > 0)
{
// Create an instance of the Author class
author = new Author
{
Name = name,
Email = email,
Country = country
};
}
}
}
if (author != null)
{
// Call the AddAuthorToFile method
AddAuthorToFile(filePath, author);
}
I select a code block that I want to refactor and ask Copilot to refactor it.
39
Copyright 2024 Mahesh Chand and CSharp Inc.
The new code generated by Copilot looks like the following:
Not only this code is optimized but it is also readable and using updated
syntaxes.
40
Copyright 2024 Mahesh Chand and CSharp Inc.
Refactor a program or application
Now, let’s try to refactor entire program.
41
Copyright 2024 Mahesh Chand and CSharp Inc.
CHAPTER 6
WRITE TEST CASES
USING COPILOT
Many programmers and developers avoid writing test cases. Copilot can be
used and write unit tests in minutes.
Try the following prompt:
You will see a new class ProgramTests is added to the project. Accept it to add
it to the program. The ProgramTests file is listed below:
using System;
using [Link];
using Xunit;
// Act
var author = [Link]();
// Assert
[Link](author);
[Link]("John Doe", [Link]);
[Link]("johndoe@[Link]", [Link]);
[Link]("USA", [Link]);
}
[Fact]
public void Test_GetAuthorDetailsFromConsole_InvalidInput_ReturnsNull()
{
// Arrange
var input = new StringReader("\n\n\n");
42
Copyright 2024 Mahesh Chand and CSharp Inc.
[Link](input);
// Act
var author = [Link]();
// Assert
[Link](author);
}
[Fact]
public void Test_AddAuthorToFile_ValidAuthor_WritesAuthorDetailsToFile()
{
// Arrange
var filePath = "C:/temp/[Link]";
var author = new Author
{
Name = "John Doe",
Email = "johndoe@[Link]",
Country = "USA"
};
// Act
[Link](filePath, author);
// Assert
var lines = [Link](filePath);
[Link](4, [Link]);
[Link]("Name: John Doe", lines[0]);
[Link]("Email: johndoe@[Link]", lines[1]);
[Link]("Country: USA", lines[2]);
[Link]("", lines[3]);
}
}
43
Copyright 2024 Mahesh Chand and CSharp Inc.
CHAPTER 7
FIX ERRORS USING
COPILOT
Copilot can help us debug the code and provide help with the errors and
exceptions in the code. Not only Copilot can explain the reason for the errors
and exceptions, but it also suggests possible solutions.
If you are new to programming or copied some old code from somewhere, you
can use Copilot to fix it and.
Let’s see this in action.
Create a C# Console Application in Visual Studio and add the following code.
Let’s assume you copied this code from Google search:
[Link]("Mahesh Chand");
}
}
Let’s say, you notice something on the following line and you are not sure
about this code:
int param1Value = [Link](args[0]);
You can ask Copilot to check it out for you.
44
Copyright 2024 Mahesh Chand and CSharp Inc.
Copilot reviews the code and answers this:
It also suggests updated code that handles non integer values of args[0].
Let’s set a breakpoint at the same line:
During debugging, on the same line, I ask Copilot the following question and it
answers that yes, there may be a problem with the code.
45
Copyright 2024 Mahesh Chand and CSharp Inc.
It also suggested the updated code.
Here is the updated code:
public static void Main(string[] args)
{
if ([Link] == 0)
{
[Link]("No arguments provided. Please provide an
argument.");
return; // Exit the method if no arguments are provided
}
int param1Value;
// Attempt to parse the first argument as an integer
if ()
{
[Link]("The provided argument is not a valid integer.");
return; // Exit the method if the argument is not a valid integer
}
46
Copyright 2024 Mahesh Chand and CSharp Inc.
}
// Ensure authors is not null before attempting to use it
if (authors != null)
{
// Safe to use authors here
}
}
Copilot also explains the new code and also suggests more questions related
to the code and suggests to modify further to handle other possible
exceptions and also suggest to add more related functionality to the program.
47
Copyright 2024 Mahesh Chand and CSharp Inc.
It explains and writes the updated code.
And as obvious, explains the newly updated code in details.
48
Copyright 2024 Mahesh Chand and CSharp Inc.
And of course, suggest more updates in the existing code including adding a
log to capture error errors in the code.
If you click on the first link, How can I modify ‘GetAuthorNameByIndex’ to
fetch author names from a database instead of a hardcoded array?, Copilot
writes full [Link] code for you that just need the connection string updated
to your database.
We will see how to build a complete data-driven application using Copilot in
the following section of this book.
49
Copyright 2024 Mahesh Chand and CSharp Inc.
Copilot suggests several changes in the code.
50
Copyright 2024 Mahesh Chand and CSharp Inc.
2. Nullable Reference Types: Marking the return type of
GetAuthorNameByIndex as string? explicitly indicates that the method can
return null. This is part of C#'s nullable reference types feature, which
helps developers write more null-safe code.
3. Simplified Array Initialization: The array of authorNames is initialized using
the new[] syntax, which is concise and clear.
4. Pattern Matching: While the provided code snippet doesn't directly benefit
from C# 9's pattern matching enhancements, keeping an eye on pattern
matching improvements in C# 12 and beyond can help simplify certain
conditional checks.
5. Expression-bodied Members: For methods like GetAuthorNameByIndex that
consist of a single expression, consider using expression-bodied members
for conciseness. This has been available since C# 7 for methods.
6. Top-level Statements: If your application's entry point (Main method) is
straightforward, you could consider using top-level statements to reduce
boilerplate code. However, since your Main method contains significant
logic, it's appropriate to keep it as is.
Remember, the adoption of new language features should be balanced with
the readability and maintainability of your code, especially in team
environments where not all members may be familiar with the latest features.
51
Copyright 2024 Mahesh Chand and CSharp Inc.
CHAPER 8
COPILOT SLASH
COMMANDS
In Visual Studio, ALT + / launches the CoPilot.
In this Window, you can type the Copilot command in plain English, or you can
use slash commands. Slash commands are a shorter version to ask Copilot to
generate content for you.
52
Copyright 2024 Mahesh Chand and CSharp Inc.
/help: Get help on Copilot chat.
/generate: Generate code to answer your question.
/tests: Create unit tests for the selected code.
def read_csv_file(file_path):
data = []
with open(file_path, 'r') as file:
reader = [Link](file)
for row in reader:
[Link](row)
return data
# Example usage
file_path = "../../../../AppData/Local/Temp/[Link]"
data = read_csv_file(file_path)
print(data)
53
Copyright 2024 Mahesh Chand and CSharp Inc.
Hit ENTER.
Copilot writes detailed explanation of the selected code.
Copilot also suggest the next steps you want to add in this code:
54
Copyright 2024 Mahesh Chand and CSharp Inc.
/doc: Add a documentation comment.
This command add comments the code.
Select the code above and type /doc command in the Copilot command
window and Hit ENTER.
def read_csv_file(file_path):
"""
Read a CSV file and return the data as a list of rows.
Args:
file_path (str): The path to the CSV file.
Returns:
list: The data from the CSV file as a list of rows.
"""
data = []
with open(file_path, 'r') as file:
reader = [Link](file)
for row in reader:
[Link](row)
return data
# Example usage
file_path = "../../../../AppData/Local/Temp/[Link]"
data = read_csv_file(file_path)
print(data)
55
Copyright 2024 Mahesh Chand and CSharp Inc.
/fix: Propose a fix for problems in the selected code.
Let’s say there is an error in the code like spelling mistake or wrong variables,
you can use /fix slash command for that.
The Copilot will show the fixed code that you may accept to fix the file.
class ReadCSVFileTestCase([Link]):
def test_read_csv_file(self):
file_path = "../../../../AppData/Local/Temp/[Link]"
expected_data = [['1', 'John', 'Doe'], ['2', 'Jane', 'Smith'], ['3',
'Bob', 'Johnson']]
with patch('[Link]',
return_value=StringIO('1,John,Doe\n2,Jane,Smith\n3,Bob,Johnson\n')) as
mock_file:
data = read_csv_file(file_path)
[Link](data, expected_data)
mock_file.assert_called_once_with(file_path, 'r')
def test_read_csv_file_empty_file(self):
file_path = "../../../../AppData/Local/Temp/[Link]"
expected_data = []
def test_read_csv_file_invalid_file(self):
file_path = "../../../../AppData/Local/Temp/[Link]"
if __name__ == '__main__':
[Link]()
After completion, Copilot also explains what optimization has done in the
selected code. It also gives you options to create a new file or preview and
replace the selected code.
57
Copyright 2024 Mahesh Chand and CSharp Inc.
Reference: scope Copilot results to a
particular file or entire solution
All the slash commands can be applied to selected code, a particular file, or
even entire solution.
To select a particular file or entire solution, you use # symbol that load all
available files and ‘Solution” option.
If you select or type #Solution, the command works for the entire solution. For
example, /optimize #Solution below will optimize the entire solution.
58
Copyright 2024 Mahesh Chand and CSharp Inc.
59
Copyright 2024 Mahesh Chand and CSharp Inc.
CHAPTER 9
CODE CONVERSION
Imagine you found some useful code, but it’s written in a different language
than you need for your project. You can use Copilot to convert your code from
one language to another. Let’s see how it is done.
I’ve a simple console app with [Link] as the main code. I want to convert
this code into C++.
I simply write the following command:
60
Copyright 2024 Mahesh Chand and CSharp Inc.
And also writes an explanation of the C++ code in details.
On this screen, you can insert this code in a new file or preview it.
Using the same method, you can easily convert code from one language to
another.
61
Copyright 2024 Mahesh Chand and CSharp Inc.
SUMMARY
Copilot is your AI buddy that is available to you all the time. It never takes
vacation. If used properly, it can boost your productivity and help you code
faster.
In this book, we discussed the basics of Copilot, how it works, and how to use
Copilot in Visual Studio. Copilot can be used in other popular IDEs as well.
You can use Copilot to learn programming in the following ways:
• Learn a new programming language from scratch as we have already
seen in the beginning of this book.
• Update your existing code to a newer version and ask Copilot to explain
it to you.
• Convert your code from one programming language to another. For
example, you can ask your Java code to convert to C# or Python.
• Fix your existing code and check for performance.
• Document and add comments to your existing code or project.
• And more
62
Copyright 2024 Mahesh Chand and CSharp Inc.
ABOUT C# CORNER
C# Corner is a prominent online community for software developers
established in 1999. Initially, it began as a small group of Microsoft technology
focused programmers but has since grown exponentially to include over 3
million registered IT professionals globally, with nearly 30 million unique
visitors annually and now covering various cutting-edge technologies including
Microsoft tech stack, cloud, mobile, blockchain, and AI.
C# Corner community focuses on its members growth by providing learning
resources, guidance, mentorship and helps members earn reputation for their
contributions.
C# Corner is a member contributions based community where members
contribute in form of sharing their code, publishing articles, blogs, tutorials,
submit training, and speak at CSharp,TV and conferences.
C# Corner soon will be accessible using [Link] URL.
63
Copyright 2024 Mahesh Chand and CSharp Inc.
The community's growth has been organic, driven by the active participation
and contributions of its members. C# Corner has become a hub for developers
to share knowledge, learn new skills, collaborate on projects, and grow in their
professional lives. The platform provides a variety of resources, including
articles, tutorials, forums, events, growth features, and conferences, which
have contributed to its popularity and widespread use.
Community Engagement:
The platform hosts forums and discussion boards where members can ask
questions, share insights, and collaborate on projects. This interactive aspect
fosters a sense of community and continuous learning among its members.
64
Copyright 2024 Mahesh Chand and CSharp Inc.
Events and Conferences:
C# Corner organizes various events, including webinars, workshops, and
conferences. These events provide opportunities for members to learn from
industry experts, network with peers, and stay updated on the latest trends
and technologies.
Local user group chapters are organized in more than 50 cities around the
world. C# Corner also hosts an annual C# Corner conference that focuses on
emerging technologies. Check out the conference website here: CSharpCorner
Annual Conference.
65
Copyright 2024 Mahesh Chand and CSharp Inc.
Download eBooks
C# Corner has a wide range of free eBooks starting from topics of C#, [Link]
and Python programming to AI and Blockchain. More new eBooks are being
added each month. Check out free eBooks library here: C# Corner eBooks
Library.
66
Copyright 2024 Mahesh Chand and CSharp Inc.
Recognition Programs:
To encourage active participation, C# Corner has recognition programs such as
the Most Valuable Professional (MVP) awards. These awards honor members
who make significant contributions to the community, thereby motivating
others to engage more actively.
[Link]
[Link] is a streaming platform dedicated to software developers.
[Link] hosts various weekly live shows, virtual conferences, and local user
group events. It also has thought leaders panel discussions on emerging
technologies. Check out [Link] here.
67
Copyright 2024 Mahesh Chand and CSharp Inc.
Challenges
C# Corner offers a variety of skill challenges designed to test and improve your
knowledge in different areas of technology. These challenges cover a wide
range of topics including C#, Azure, Docker, Kubernetes, and more. Each
challenge allows you to earn badges and showcase them on your profile,
providing a fun and competitive way to learn and demonstrate your skills.
Check out Challenges here: C# Corner - Skills Challenges.
68
Copyright 2024 Mahesh Chand and CSharp Inc.
Certifications
C# Corner offers various certifications and skill challenges aimed at developers
looking to enhance their expertise in different areas of technology. These
certifications can be earned through completing specific challenges and
courses available on the C# Corner platform. Check out Certifications here:
Get Certified! Certified Developers!.
69
Copyright 2024 Mahesh Chand and CSharp Inc.
HackIndia
HackIndia 2024 is a large-scale hackathon organized by CSharpCorner, a global
community of software developers. It is focused on Web3 and AI technologies,
running from May to October 2024. The event brings together over 9,000
students from various universities across India, competing for $150,000 in
prizes. Participants gain insights from 36 speakers, guidance from 72 judges
and mentors, and opportunities to showcase their skills and innovation in
Web3 and AI. The final event will be held in Delhi in October 2024.
HackIndia Website: HackIndia 2024 - India's Biggest Web3 Hackathon
70
Copyright 2024 Mahesh Chand and CSharp Inc.
Students Portal
Student Portal is designed for college students to get help with learning new
technologies, signup for new learning courses, participate in skills challenges,
find, and apply for internships and participate in hackathons. Check out
[Link] Student Portal.
Join Today!
We’re calling for professionals to become active community members. C#
Corner’s mission is to provide software professionals with a single platform to
learn, share, collaborate, and growth.
Become a C# Corner Member Today!
71
Copyright 2024 Mahesh Chand and CSharp Inc.