C# for beginners

C# - for beginners - Speaking C# , ANGULAR WITH CORE .NET AND MVC RAZOR ENGINE
This chapter is all about the basics of the C# programming language. Over the course
of this chapter, you'll learn how to write statements using the grammar of C#, as well
as being introduced to some of the common vocabularies that you will use every day.
In addition to this, by the end of the chapter, you'll feel confident in knowing how to
temporarily store and work with information in your computer's memory.
This chapter covers the following topics:
• Introducing C#
• Understanding the basics of C#
• Working with variables
• Working with null values
• Further exploring console applications

Introducing C #

This part of the book is about the C# language—the grammar and vocabulary that
you will use every day to write the source code for your applications.
Programming languages have many similarities to human languages, except that in

programming languages, you can make up your own words

Understanding language versions and features


This part of the book covers the C# programming language and is written primarily
for beginners, so it covers the fundamental topics that all developers need to know,
from declaring variables to storing data to how to define your own custom data types.
Advanced and obscure topics like ref local variable reassignment and reference
semantics with value types are not covered.
This book covers features of the C# language from version 1.0 up to the latest
version, 8.0. If you already have some familiarity with older versions of C# and
are excited to find out about the new features in the most recent versions of C#, I
have made it easier for you to jump around by listing language versions and their
important new features below, along with the chapter number and topic title where
you can learn about them.

Discovering your C# compiler versions


With the C# 7.x generation, Microsoft decided to increase the cadence of the language
releases, releasing minor version numbers, also known as point releases, for the first
time since C# 1.1.
.NET language compilers for C#, Visual Basic, and F#, also known as Roslyn, are
distributed as part of the .NET Core SDK. To use a specific version of C#, you must have
at least that version of .NET Core SDK installed, as shown in the following table:
.NET Core SDK Roslyn C#
1.0.4 2.0 - 2.2 7.0
1.1.4 2.3 - 2.4 7.1
2.1.2 2.6 - 2.7 7.2
2.1.200 2.8 - 2.10 7.3
3.0 3.0 - 3.3 8.0

Understanding C# grammar

In English, we indicate the end of a sentence with a full stop. A sentence can be
composed of multiple words and phrases, with the order of words being part of the
grammar. For example, in English, we say: "the black cat."
The adjective, black, comes before the noun, cat. Whereas French grammar has
a different order; the adjective comes after the noun, "le chat noir." What's important
to take away from this is that the order matters.
C# indicates the end of a statement with a semicolon. A statement can be composed
of multiple variables and expressions. For example, in the following statement,
totalPrice is a variable and subtotal + salesTax is an expression:
var totalPrice = subtotal + salesTax;
The expression is made up of an operand named subtotal, an operator +, and
another operand named salesTax. The order of operands and operators matters.

Comments


When writing your code, you're able to add comments to explain your code using
a double slash, //. By inserting // the compiler will ignore everything after the //

until the end of the line, as shown in the following code

// sales tax must be added to the subtotal
var totalPrice = subtotal + salesTax;
Visual Studio Code will add or remove the comment double slashes at the start of
the currently selected line(s) if you press Ctrl + K + C to add them or Ctrl + K + U to
remove them. In macOS, press Cmd instead of Ctrl.
To write a multiline comment, use /* at the beginning and */ at the end of the
comment, as shown in the following code:
/*
This is a multi-line
comment.
*/


Blocks

In English, we indicate a paragraph by starting a new line. C# indicates a block of
code with the use of curly brackets, { }. Blocks start with a declaration to indicate
what it is being defined. For example, a block can define a namespace, class, method,
or a statement, something we will learn more about later.
In your current project, note that the grammar of C# is written for you by the
dotnet CLI tool. I've added some comments to the statements written by the project
template, as shown in the following code:
using System; // a semicolon indicates the end of a statement
namespace Basics
{
class Program
{
static void Main(string[] args)
{ // the start of a block
Console.WriteLine("Hello World!"); // a statement
} // the end of a block
}
}

Verbs are methods

In English, verbs are doing or action words, like run and jump. In C#, doing or action
words are called methods. There are hundreds of thousands of methods available to
C#. In English, verbs change how they are written based on when in time the action
happens. For example, Amir was jumping in the past, Beth jumps in the present, they
jumped in the past, and Charlie will jump in the future.
In C#, methods such as WriteLine change how they are called or executed based
on the specifics of the action. This is called overloading, which is something we will
cover in more detail during Chapter 5, Building Your Own Types with Object-Oriented
Programming. But for now, consider the following example:
// outputs a carriage-return
Console.WriteLine();

// outputs the greeting and a carriage-return
Console.WriteLine("Hello Sarad");
// outputs a formatted number and date and a carriage-return
Console.WriteLine(
"Temperature on {0:D} is {1}°C.", DateTime.Today, 23.4);
A different analogy is that some words are spelled the same, but have different
meanings depending on the context.
Nouns are types, fields, and variables
In English, nouns are names that refer to things. For example, Fido is the name of
a dog. The word "dog" tells us the type of thing that Fido is, and so in order for Fido
to fetch a ball, we would use his name.
In C#, their equivalents are types, fields, and variables. For example, Animal and
Car are types; that is, they are nouns for categorizing things. Head and Engine
are fields, that is, nouns that belong to Animal and Car. Whilst Fido and Bob are
variables, that is, nouns for referring to a specific thing.
There are tens of thousands of types available to C#, though have you noticed how
I didn't say, "There are tens of thousands of types in C#?" The difference is subtle
but important. The language of C# only has a few keywords for types, such as
string and int, and strictly speaking, C# doesn't define any types. Keywords such
as string that look like types are aliases, which represent types provided by the
platform on which C# runs.
It's important to know that C# cannot exist alone; after all, it's a language that runs
on variants of .NET. In theory, someone could write a compiler for C# that uses a
different platform, with different underlying types. In practice, the platform for C#
is .NET, which provides tens of thousands of types to C#, including System.Int32,
which is the C# keyword alias int maps to, as well as many more complex types,
such as System.Xml.Linq.XDocument.
It's worth taking note that the term type is often confused with class. Have you
ever played the parlor game Twenty Questions, also known as Animal, Vegetable,
or Mineral? In the game, everything can be categorized as an animal, vegetable, or
mineral. In C#, every type can be categorized as a class, struct, enum, interface,
or delegate. The C# keyword string is a class, but int is a struct. So, it is best to
use the term type to refer to both.
Revealing the extent of the C# vocabulary
We know that there are more than one hundred keywords in C#, but how many
types are there? Let's now write some code in order to find out how many types
(and their methods) are available to C# in our simple console application.

Don't worry about how this code works for now; it uses a technique called reflection.
1. We'll start by adding the following statements at the top of the Program.cs
file, as shown in the following code:
using System.Linq;
using System.Reflection;
2. Inside the Main method, delete the statement that writes Hello World! and
replace it with the following code:
// loop through the assemblies that this app references
foreach (var r in Assembly.GetEntryAssembly()
.GetReferencedAssemblies())
{
// load the assembly so we can read its details
var a = Assembly.Load(new AssemblyName(r.FullName));
// declare a variable to count the number of methods
int methodCount = 0;
// loop through all the types in the assembly
foreach (var t in a.DefinedTypes)
{
// add up the counts of methods
methodCount += t.GetMethods().Count();
}
// output the count of types and their methods
Console.WriteLine(
"{0:N0} types with {1:N0} methods in {2} assembly.",
arg0: a.DefinedTypes.Count(),
arg1: methodCount,
arg2: r.Name);
}
3. Navigate to View | Terminal.
4. In TERMINAL, enter the following command:
dotnet run
5. After running that command, you will see the following output, which
shows the actual number of types and methods that are available to you in
the simplest application when running on macOS. The numbers of types and
methods displayed may be different depending on the operating system that
you are using, as shown in the following output:
30 types with 325 methods in System.Runtime assembly.
99 types with 1,068 methods in System.Linq assembly.
56 types with 691 methods in System.Console assembly.


6. Add statements to the top of the Main method to declare some variables,
as shown highlighted in the following code:
static void Main(string[] args)
{
// declare some unused variables using types
// in additional assemblies
System.Data.DataSet ds;
System.Net.Http.HttpClient client;
By declaring variables that use types in other assemblies, those assemblies
are loaded with our application, which allows our code to see all the types
and methods in them. The compiler will warn you that you have unused
variables but that won't stop your code from running.
7. Run the console application again and view the results, which should look
similar to the following output:
30 types with 325 methods in System.Runtime assembly.
371 types with 6,735 methods in System.Data.Common assembly.
406 types with 4,228 methods in System.Net.Http assembly.
99 types with 1,068 methods in System.Linq assembly.
56 types with 691 methods in System.Console assembly.
Now, you have a better sense of why learning C# is a challenge because there are so
many types and methods to learn. Methods are only one category of a member that a
type can have, and other programmers are constantly defining new members!
Working with variables
All applications process data. Data comes in, data is processed, and then data goes
out. Data usually comes into our program from files, databases, or user input,
and it can be put temporarily into variables that will be stored in the memory of
the running program. When the program ends, the data in memory is lost. Data
is usually output to files and databases, or to the screen or a printer. When using
variables, you should think about, firstly, how much space it takes in the memory,
and, secondly, how fast it can be processed.
We control this by picking an appropriate type. You can think of simple common
types such as int and double as being different-sized storage boxes, where a smaller
box would take less memory but may not be as fast at being processed; for example,
adding 16-bit numbers might not be processed as fast as adding 64-bit numbers on a
64-bit operating system. Some of these boxes may be stacked close by, and some may
be thrown into a big heap further away.

Comments

Popular posts from this blog

How to disable table row in Angular

How to create XML file dynamically in c#.net?

How to get Array value in Angular ?