Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Learn C# Programming
Learn C# Programming

Learn C# Programming: A guide to building a solid foundation in C# language for writing efficient programs

Arrow left icon
Profile Icon Marius Bancila Profile Icon Tripathi Profile Icon Rialdi Profile Icon Ankit Sharma
Arrow right icon
£9.99 per month
Full star icon Full star icon Full star icon Full star icon Full star icon 5 (4 Ratings)
Paperback Apr 2020 636 pages 1st Edition
eBook
£26.99
Paperback
£32.99
Subscription
Free Trial
Renews at £9.99p/m
Arrow left icon
Profile Icon Marius Bancila Profile Icon Tripathi Profile Icon Rialdi Profile Icon Ankit Sharma
Arrow right icon
£9.99 per month
Full star icon Full star icon Full star icon Full star icon Full star icon 5 (4 Ratings)
Paperback Apr 2020 636 pages 1st Edition
eBook
£26.99
Paperback
£32.99
Subscription
Free Trial
Renews at £9.99p/m
eBook
£26.99
Paperback
£32.99
Subscription
Free Trial
Renews at £9.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $15.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Learn C# Programming

Chapter 2: Data Types and Operators

In the previous chapter, we learned about .NET Framework and understood the basic structure of a C# program. In this chapter, we will learn about data types and objects in C#. Alongside control statements, which we will explore in the next chapter, these are the building blocks of every program. We will discuss built-in data types, explain the difference between value types and reference types, and learn how to convert between types. We will also discuss the operators defined by the language as we move on.

The following topics will be covered in this chapter:

  • Basic built-in data types
  • Variables and constants
  • Reference types and value types
  • Nullable type
  • Arrays
  • Type conversion
  • Operators

By the end of this chapter, you will be able to write a simple C# program using the aforementioned language features.

Basic data types

In this section, we will explore the basic data types. The Common Language Infrastructure (CLI) defines a set of standard types and operations that are supported by all programming languages targeting the CLI. These data types are provided in the System namespace. All of them, however, have a C# alias. These aliases are keywords in the C# language, which means they can only be used in the context of their designated purpose and not elsewhere, such as variable, class, or method names. The C# name and the .NET name, along with a short description of each type, are listed in the following table (listed alphabetically by the C# name):

The types listed in this table are called simple types or primitive types. Apart from these, there are two more built-in types:

Let's explore all of the primitive types in detail in the following sections.

The integral types

C# supports eight integer types that represent various...

Variables

Variables are defined as a named memory location that can be assigned to a value. There are several types of variables, including the following:

  • Local variables: These are variables that are defined within a method and their scope is local to that method.
  • Method parameters: These are variables that hold the arguments passed to a method during a function call.
  • Class fields: These are variables that are defined in the scope of the class and are accessible to all of the class methods and depending on the accessibility of the field to other classes too.
  • Array elements: These are variables that refer to elements in an array.

In this section, we will refer to local variables, which are variables declared in the body of a function. Such variables are declared using the following syntax:

datatype variable_name;

In this statement, datatype is the data type of the variable and variable_name is the name of the variable. Here are several examples:

...

Understanding constants

There are some scenarios in which we do not want to change the value of a variable after it is initialized. Examples can include mathematical constants (pi, Euler's number, and so on), physical constants (Avogadro's number, the Boltzmann constant, and so on), or any application-specific constants (the maximum allowed number of logins, the maximum number of retries for a failed operation, status codes, and many others). C# provides us with constant variables for this purpose. Once defined, the value of a constant variable cannot be changed during its scope. If you try to change the value of a constant variable after it is initialized, the compiler will throw an error.

To make a variable constant, we need to prefix it with the const keyword. The constant variables must be initialized at the time of declaration. Here is an example of an integer constant initialized with the value 42:

const int a = 42;

It is important to note that only the built...

Reference types and value types

The data types in C# are divided into value types and reference types. There are several important differences between these two, such as copy semantics. We will look at these in detail in the following sections.

Value types

A variable of a value type contains the value directly. When a value type variable is assigned from another, the stored value is copied. The primitive data types we have seen earlier are all value types. All user-defined types declared as structures (with the struct keyword) are value types. Although all types are implicitly derived from the object, type value types do not support explicit inheritance, which is a topic discussed in Chapter 4, Understanding the Various User-Defined Types.

Let's see an example here:

int a = 20;
DateTime dt = new DateTime(2019, 12, 25);

Value types are typically stored on the stack in memory, although this is an implementation detail and not a characteristic of value types. If you...

Nullable types

Reference types have the default value null, which indicates that a variable is not assigned to the instance of any object. Value types do not have such an option. However, there are cases when no value is a valid value for a value type too. To represent such cases, you can use a nullable type.

A nullable type is an instance of System.Nullable<T>, a generic value type that can represent the values of an underlying T type, which can only be a value type, as well as an additional null value. The following sample shows a few examples:

Nullable<int> a;
Nullable<int> b = null;
Nullable<int> c = 42;

You can use the shorthand syntax, T?, instead of Nullable<T>; these two are interchangeable. The following examples are alternatives for the preceding ones:

int? a;
int? b = null;
int? c = 42;

You can use the HasValue property to check whether a nullable type object has a value, and Value to access the underlying value:

if (c.HasValue...

Arrays

An array is a data structure that holds multiple values (including zero or a single one) of the same data type. It is a fixed-size sequence of homogeneous elements that are stored in contiguous memory locations. Arrays in C# are zero-indexed, meaning that the position of the first element of an array is zero and the position of the last element of the array is a total number of elements minus one.

The array type is a reference type and therefore arrays are allocated on the heap. The default value for the elements of numeric arrays is zero and for arrays of reference types, the default value is null. The type of the elements of an array can be of any type, including another array type.

Arrays in C# can be one-dimensional, multi-dimensional, or jagged. Let's explore these in detail.

One-dimensional arrays

A one-dimensional array can be defined using the syntax datatype[] variable_name. Arrays can be initialized when they are declared. If an array variable is not...

Type conversion

Sometimes we need to convert one data type into another, and that is where type conversion comes in picture. Type conversion can be classified into several categories:

  • Implicit type conversion
  • Explicit type conversion
  • User-defined conversions
  • Conversions with helper classes

Let's explore these in detail.

Implicit type conversion

For built-in numeric types, when we assign the value of a variable to one of another data type, implicit type conversion occurs if both types are compatible and the range of destination type is more than that of the source type. For example, int and float are compatible types. Therefore, we can assign an integer variable to a variable of the float type. Similarly, the double type is large enough to hold values from any other numerical type, including long and float, as shown in the following example:

int i = 10;
float f = i;
long l = 7195467872;
double d = l;

The following table shows the implicit...

Operators

C# provides an extensive set of operators for built-in types. Operators are broadly classified in the following categories: arithmetic, relational, logical, bitwise, assignment, and other operators. Some operators can be overloaded for user-defined types. This topic will be further discussed in Chapter 5, Object-Oriented Programming in C#.

When evaluating an expression, operator precedence and associativity determine the order in which the operations are performed. You can change this order by using parentheses, just like you would do with a mathematical expression.

The following table lists the order of the operators with the highest precedence at the top and the lowest at the bottom. Operators that are listed together, on the same row, have equal precedence:

For operators with the same precedence, associativity determines which one is evaluated first. There are two types of associativity:

  • Left-associativity: This determines operators...

Summary

In this chapter, we learned about built-in data types in C#, which are the numerical types, floating-point types, Boolean and character types, string, and object. Moreover, we also covered nullable types and array types. We learned about variables and constants and looked at the differences between value types and reference types. In addition to this, we covered the concepts of type conversion and casting. At the end of this chapter, we learned about the various types of operators available in C#.

In the next chapter, we will explore control statements and exceptions in C#.

Test what you learned

  1. What are the integral built-in types in C#?
  2. What are the differences between the floating-point types and the decimal type?
  3. How do you concatenate strings?
  4. What are escape sequences and how are they related to verbatim strings?
  5. What is an implicitly typed variable? Can these variables be initialized with null?
  6. What are value types? What are reference types? What are the main differences between them?
  7. What are boxing and unboxing?
  8. What is a nullable type and how do you declare a nullable integer variable?
  9. How many types of arrays exist and what is the difference between them?
  10. What are the available type conversions and how do you provide user-defined type conversion?
Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Learn the fundamentals of C# with the help of easy-to-follow examples and explanations
  • Leverage the latest features of C# 8, including nullable reference types, pattern matching enhancements, and asynchronous streams
  • Explore object-oriented programming, functional programming, and multithreading concepts

Description

The C# programming language is often developers’ primary choice for creating a wide range of applications for desktop, cloud, and mobile. In nearly two decades of its existence, C# has evolved from a general-purpose, object-oriented language to a multi-paradigm language with impressive features. This book will take you through C# from the ground up in a step-by-step manner. You'll start with the building blocks of C#, which include basic data types, variables, strings, arrays, operators, control statements, and loops. Once comfortable with the basics, you'll then progress to learning object-oriented programming concepts such as classes and structures, objects, interfaces, and abstraction. Generics, functional programming, dynamic, and asynchronous programming are covered in detail. This book also takes you through regular expressions, reflection, memory management, pattern matching, exceptions, and many other advanced topics. As you advance, you'll explore the .NET Core 3 framework and learn how to use the dotnet command-line interface (CLI), consume NuGet packages, develop for Linux, and migrate apps built with .NET Framework. Finally, you'll understand how to run unit tests with the Microsoft unit testing frameworks available in Visual Studio. By the end of this book, you’ll be well-versed with the essentials of the C# language and be ready to start creating apps with it.

Who is this book for?

If you have little experience in coding or C# and want to learn the essentials of C# programming to develop powerful programming techniques, this book is for you. It will also help aspiring programmers to write scripts or programs to accomplish specific tasks.

What you will learn

  • Get to grips with all the new features of C# 8
  • Discover how to use attributes and reflection to build extendable applications
  • Utilize LINQ to uniformly query various sources of data
  • Use files and streams and serialize data to JSON and XML
  • Write asynchronous code with the async-await pattern
  • Employ .NET Core tools to create, compile, and publish your applications
  • Create unit tests with Visual Studio and the Microsoft unit testing frameworks

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Apr 30, 2020
Length: 636 pages
Edition : 1st
Language : English
ISBN-13 : 9781789805864
Vendor :
Microsoft
Category :
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $15.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Apr 30, 2020
Length: 636 pages
Edition : 1st
Language : English
ISBN-13 : 9781789805864
Vendor :
Microsoft
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
£9.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 6,500+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
£99.99 billed annually
Feature tick icon Unlimited access to Packt's library of 6,500+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just £5 each
Feature tick icon Exclusive print discounts
£139.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 6,500+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just £5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total £ 131.97
C# 10 and .NET 6 – Modern Cross-Platform Development
£59.99
Learn C# Programming
£32.99
Clean Code in C#
£38.99
Total £ 131.97 Stars icon
Visually different images

Table of Contents

19 Chapters
Chapter 1: Starting with the Building Blocks of C# Chevron down icon Chevron up icon
Chapter 2: Data Types and Operators Chevron down icon Chevron up icon
Chapter 3: Control Statements and Exceptions Chevron down icon Chevron up icon
Chapter 4: Understanding the Various User-Defined Types Chevron down icon Chevron up icon
Chapter 5: Object-Oriented Programming in C# Chevron down icon Chevron up icon
Chapter 6: Generics Chevron down icon Chevron up icon
Chapter 7: Collections Chevron down icon Chevron up icon
Chapter 8: Advanced Topics Chevron down icon Chevron up icon
Chapter 9: Resource Management Chevron down icon Chevron up icon
Chapter 10: Lambdas, LINQ, and Functional Programming Chevron down icon Chevron up icon
Chapter 11: Reflection and Dynamic Programming Chevron down icon Chevron up icon
Chapter 12: Multithreading and Asynchronous Programming Chevron down icon Chevron up icon
Chapter 13: Files, Streams, and Serialization Chevron down icon Chevron up icon
Chapter 14: Error Handling Chevron down icon Chevron up icon
Chapter 15: New Features of C# 8 Chevron down icon Chevron up icon
Chapter 16: C# in Action with .NET Core 3 Chevron down icon Chevron up icon
Chapter 17: Unit Testing Chevron down icon Chevron up icon
Assessments Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Full star icon 5
(4 Ratings)
5 star 100%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
Cliente Amazon Nov 03, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Da regalare a mio Figlio per lo studio universitario sui linguaggi ad oggetti e in particolare C#. D'altronde sec come Co-Autore c'è il Mitico Raf allora è una garanzia. WeLoveRaf!!!
Amazon Verified review Amazon
Keerthi Jan 25, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Honestly I despise Packt due to bad experiences in the past. But this book is an exception.I come from the Java world and was looking to get started on the .NET platform to build micro-services in C# for a project requirement. After trying a couple of books on the topic from O'Reilly and disappointed picked this one half-heatedly.This book blew the rest out of the water easily. Concepts that the other books struggle to explain or not explained well enough are dealt with in a lucid and clear manner. The authors communicate more with less words. The breadth and depth of coverage is also good and, most importantly, is free from fluff. Highly recommended!Would never judge a book by its cover, ever!
Amazon Verified review Amazon
S. Barth Aug 02, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I bought this book for my grandson who is learning Unity game development. (Unity uses C# as the code base.) The book arrived quickly, in perfect shape, and will be a great asset / resource as we start off his developer's library with it. A good purchase all the way around!
Amazon Verified review Amazon
Thomas Seabrook Jul 19, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I was in need of learning the basics and some intermediate topics of C# and so far this book hasn't dissapointed. After looking through some underwhelming reviews of similar books I stumbled across this one and though it was worth a go. So far I haven't been dissapointed. The book is well written and doesn't waste much time before getting into the learning content (there's a chapter on the history of the language). Overall this is a great read for anyone starting to learn C# and I can myself reffering to this book for a long while.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.