C# Basics
C# is a versatile programming language developed by Microsoft, widely used for building a variety of applications, from web to desktop and mobile. This post covers the basics of C#, including syntax, data types, and object-oriented programming concepts. Dotnet is a framework that supports C# and provides a rich set of libraries and tools for developers.
Console commands
C# can be extended a lot by using the dotnet CLI here are some examples of the .net CLI commands.
The .NET CLI (Command-Line Interface) is a powerful tool for developing, building, running, and managing .NET applications. Here’s a concise overview of some commonly used .NET CLI commands:
Basic commands
dotnet new
: Creates a new project or solution based on a specified template.- Example:
dotnet new console
(creates a new console application)
- Example:
dotnet build
: Builds the project and its dependencies.- Example:
dotnet build
(builds the current project)
- Example:
dotnet run
: Runs the application.- Example:
dotnet run
(runs the current project)
- Example:
dotnet restore
: Restores the dependencies and tools of a project.- Example:
dotnet restore
(restores packages for the current project)
- Example:
dotnet publish
: Packs the application and its dependencies into a folder for deployment.- Example:
dotnet publish -c Release
(publishes the project in Release configuration)
- Example:
Project Management
dotnet add package
: Adds a NuGet package to the project.- Example:
dotnet add package Newtonsoft.Json
(adds the Newtonsoft.Json package)
- Example:
dotnet remove package
: Removes a NuGet package from the project.- Example:
dotnet remove package Newtonsoft.Json
(removes the Newtonsoft.Json package)
- Example:
dotnet list package
: Lists the packages referenced by the project.- Example:
dotnet list package
(lists all packages in the current project)
- Example:
Solution Management
dotnet sln
: Manages solutions.- Example:
dotnet sln add MyProject.csproj
(adds a project to the solution)
- Example:
dotnet sln remove
: Removes a project from the solution.- Example:
dotnet sln remove MyProject.csproj
(removes a project from the solution)
- Example:
Testing
dotnet test
: Runs unit tests in the project.- Example:
dotnet test
(runs tests in the current project)
- Example:
Global Tools
dotnet tool install
: Installs a .NET global tool.- Example:
dotnet tool install -g dotnet-ef
(installs the Entity Framework Core CLI tool globally)
- Example:
dotnet tool update
: Updates a .NET global tool.- Example:
dotnet tool update -g dotnet-ef
(updates the Entity Framework Core CLI tool)
- Example:
dotnet tool list
: Lists installed global tools.- Example:
dotnet tool list -g
(lists all globally installed tools)
- Example:
Help and Information
dotnet --info
: Displays information about the .NET SDK and runtime installed on the machine.- Example:
dotnet --info
- Example:
dotnet help
: Displays help information for the .NET CLI.- Example:
dotnet help
ordotnet <command> --help
(provides help for a specific command)
- Example:
Syntax
C# syntax is similar to other C-style languages like Java and C++. Here are some basic elements:
Variables: Declared with a type followed by the variable name.
Data Types: C# has several built-in data types, including:
int
: Represents integer values.double
: Represents floating-point numbers.bool
: Represents boolean values (true
orfalse
).string
: Represents a sequence of characters.
Control Structures: C# supports various control structures, such as:
- If statements: Used for conditional execution.
- For loops: Used for iterating over a range of values.
- Switch statements: Used for selecting one of many code blocks to execute.
Functions: Defined using the
void
keyword for functions that do not return a value, or with a specific return type.Classes and Objects: C# is an object-oriented language, allowing you to define classes and create objects.
Top level statements in C#
Top-level statements in C# are a feature introduced in C# 9.0 that allows developers to write simple programs without the need for explicitly defining a class or a Main
method. This feature is particularly useful for small applications, scripts, or quick prototypes, making the code cleaner and more concise.
Key Features of Top-Level Statements
- Simplified Syntax: You can write code directly in the file without wrapping it in a class or a method. This reduces boilerplate code and makes it easier to get started.
- Single Entry Point: The compiler automatically generates a
Main
method behind the scenes, which serves as the entry point for the application. - Namespace and Usings: You can still use namespaces and
using
directives at the top of the file, but you don’t need to define a class to contain your code. - Variable Declarations: You can declare variables, use control flow statements, and call methods directly at the top level.
Example of Top-Level Statements
Here’s a simple example of a C# program using top-level statements:
Explanation of the Example
- Using Directive: The
using System;
directive allows you to use classes from theSystem
namespace without needing to fully qualify them. - Direct Code Execution: The
Console.WriteLine
statements and thefor
loop are written directly in the file, without needing to define a class or aMain
method. - Automatic Main Method: The C# compiler treats this code as if it were inside a
Main
method of a generated class, allowing it to run as a standard console application.
- Using Directive: The
Limitations
- No Multiple Entry Points
- Not Suitable for Large Applications
- Cannot Use
async
Directly: You cannot declare anasync
method directly at the top level. However, you can useasync
within a method that you define.
Preprocessor Directives
C# supports preprocessor directives, which are commands that are processed before the compilation of the code
- Using Directives: Used to include namespaces in your code.
1
using System;
- Conditional Compilation: Allows you to include or exclude code based on certain conditions.
Basic IO statements
C# provides several methods for input and output operations:
Console Input/Output: The
Console
class provides methods for reading from and writing to the console.- Taking in a number: You can read a number from the console and convert it to an integer.
Datatypes
C# is a statically typed language, which means that the type of a variable is known at compile time. C# provides a rich set of built-in data types, which can be categorized into two main groups: Value Types and Reference Types. Below is a detailed look at these data types.
- Integral Types
a.
int
- Definition and Range: Represents a 32-bit signed integer. Range: -2,147,483,648 to 2,147,483,647.
- Snippet:
1
int myInt = 42;
b.
long
- Definition and Range: Represents a 64-bit signed integer. Range: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
- Snippet:
1
long myLong = 12345678901234L;
c.
short
- Definition and Range: Represents a 16-bit signed integer. Range: -32,768 to 32,767.
- Snippet:
1
short myShort = 32000;
d.
byte
- Definition and Range: Represents an 8-bit unsigned integer. Range: 0 to 255.
- Snippet:
1
byte myByte = 255;
e.
sbyte
- Definition and Range: Represents an 8-bit signed integer. Range: -128 to 127.
- Snippet:
1
sbyte mySByte = -128;
f.
uint
- Definition and Range: Represents a 32-bit unsigned integer. Range: 0 to 4,294,967,295.
- Snippet:
1
uint myUInt = 4000000000U;
g.
ulong
- Definition and Range: Represents a 64-bit unsigned integer. Range: 0 to 18,446,744,073,709,551,615.
- Snippet:
1
ulong myULong = 8000000000000000000UL;
h.
ushort
- Definition and Range: Represents a 16-bit unsigned integer. Range: 0 to 65,535.
- Snippet:
1
ushort myUShort = 65000;
- Floating-Point Types
a.
float
- Definition and Range: Represents a single-precision (32-bit) floating-point number. Range: ±1.5 × 10^−45 to ±3.4 × 10^38.
- Snippet:
1
float myFloat = 3.14f;
b.
double
- Definition and Range: Represents a double-precision (64-bit) floating-point number. Range: ±5.0 × 10^−324 to ±1.7 × 10^308.
- Snippet:
1
double myDouble = 3.14159265358979;
c.
decimal
- Definition and Range: Represents a 128-bit precise decimal value with 28-29 significant digits. Range: ±1.0 × 10^−28 to ±7.9 × 10^28.
- Snippet:
1
decimal myDecimal = 19.99m;
- Other Value Types
- Reference Types
a.
string
- Definition: Represents a sequence of characters. Strings are immutable.
- Snippet:
1
string myString = "Hello, World!";
b. Array
- Definition: A collection of items of the same type. Can be single-dimensional or multi-dimensional.
- Snippet:
1
int[] myArray = new int[5] { 1, 2, 3, 4, 5 };
c. Class
- Definition: A user-defined reference type that can contain data members (fields) and function members (methods).
- Snippet:
d. Interface
- Definition: A contract that defines a set of methods and properties that implementing classes must provide.
- Snippet:
e. Delegate
- Definition: A type that represents references to methods with a specific parameter list and return type.
- Snippet:
1
public delegate void Notify();
f.
object
- Definition: The base type from which all other types derive. Can hold any data type.
- Snippet:
1
object myObject = "This is an object";
- Nullable Types
- a.
int?
- Definition: A nullable integer that can represent all the values of its underlying type plus an additional
null
value. - Snippet:
1
int? myNullableInt = null;
- Definition: A nullable integer that can represent all the values of its underlying type plus an additional
- Enumerations
- a.
enum
- Definition: A special “class” that represents a group of constants (named values).
- Snippet:
1
enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }
Logical statements
Logical statements or conditions help the flow of the code that is running within the program. Here are the examples of some logical statements that are in C#
- Logical Operators
a.
&&
(Logical AND)- Definition: Returns
true
if both operands are true; otherwise, it returnsfalse
. - Snippet:
- Definition: Returns
b.
||
(Logical OR)- Definition: Returns
true
if at least one of the operands is true; returnsfalse
if both are false. - Snippet:
- Definition: Returns
c.
!
(Logical NOT)- Definition: Reverses the logical state of its operand. If the condition is true, it becomes false, and vice versa.
- Snippet:
- Conditional Statements
a.
if
Statement- Definition: Executes a block of code if the specified condition is true.
- Snippet:
b.
else
Statement- Definition: Executes a block of code if the condition in the
if
statement is false. - Snippet:
- Definition: Executes a block of code if the condition in the
c.
else if
Statement- Definition: Specifies a new condition to test if the first condition is false.
- Snippet:
- Switch Statement
- a.
switch
- Definition: Selects one of many code blocks to execute based on the value of a variable or expression.
- Snippet:
- Notes: Unlike other compilers C# requires the user to include the break statement within the default statement also.
- Ternary Operator
- a.
?:
(Ternary Conditional Operator)- Definition: A shorthand for
if-else
statements that returns one of two values based on a condition. - Snippet:
- Definition: A shorthand for
Data structures in C#
- Arrays
- Definition: A collection of items of the same type, stored in contiguous memory locations. Arrays can be single-dimensional or multi-dimensional.
- Snippet:
1
int[] myArray = new int[5] { 1, 2, 3, 4, 5 }; // Single-dimensional array
- Lists
- Definition: A dynamic array that can grow and shrink in size. It is part of the
System.Collections.Generic
namespace and provides methods for adding, removing, and searching for elements. - Snippet:
- Dictionaries
- Definition: A collection of key-value pairs, where each key is unique. It allows for fast lookups based on keys. It is also part of the
System.Collections.Generic
namespace. - Snippet:
- HashSet
- Definition: A collection of unique elements that provides high-performance set operations. It does not allow duplicate values and is part of the
System.Collections.Generic
namespace. - Snippet:
- Queue
- Definition: A first-in, first-out (FIFO) collection of objects. It is part of the
System.Collections.Generic
namespace and provides methods for adding and removing elements. - Snippet:
- Stack
- Definition: A last-in, first-out (LIFO) collection of objects. It allows adding and removing elements from the top of the stack.
- Snippet:
- LinkedList
- Definition: A doubly linked list that allows for efficient insertions and deletions. It is part of the
System.Collections.Generic
namespace. - Snippet:
- Tuple
- Definition: A data structure that can hold a fixed number of items of different types. It is useful for returning multiple values from a method.
- Snippet:
1
var myTuple = Tuple.Create(1, "Alice", 30); // Tuple with an int, string, and int
- ArrayList
- Definition: A non-generic collection that can hold items of any type. It is part of the
System.Collections
namespace and is less type-safe than generic collections. - Snippet:
String functions in C#
The following are some of the string functions in C#.
Length
- Definition: Gets the number of characters in the string.
- Snippet:
Substring
- Definition: Returns a substring from the string, starting at a specified index and optionally for a specified length.
- Snippet:
IndexOf
- Definition: Returns the zero-based index of the first occurrence of a specified substring. Returns -1 if not found.
- Snippet:
LastIndexOf
- Definition: Returns the zero-based index of the last occurrence of a specified substring. Returns -1 if not found.
- Snippet:
Replace
- Definition: Replaces all occurrences of a specified substring with another substring.
- Snippet:
ToUpper
- Definition: Converts the string to uppercase.
- Snippet:
ToLower
- Definition: Converts the string to lowercase.
- Snippet:
Trim
- Definition: Removes all leading and trailing whitespace characters from the string.
- Snippet:
Split
- Definition: Splits the string into an array of substrings based on specified delimiters.
- Snippet:
Join
- Definition: Concatenates the elements of a string array, using a specified separator between each element.
- Snippet:
Contains
- Definition: Determines whether the string contains a specified substring.
- Snippet:
StartsWith
- Definition: Determines whether the string starts with a specified substring.
- Snippet:
EndsWith
- Definition: Determines whether the string ends with a specified substring.
- Snippet:
Format
- Definition: Formats the specified string by replacing the format items with the string representation of the corresponding objects.
- Snippet:
Equals
- Definition: Determines whether two string instances have the same value.
- Snippet:
IsNullOrEmpty
- Definition: Determines whether a specified string is
null
or an empty string. - Snippet:
IsNullOrWhiteSpace
- Definition: Determines whether a specified string is
null
, empty, or consists only of white-space characters. - Snippet:
Package manager in C#
In the C#/.NET ecosystem, the primary package manager is NuGet. It is an essential tool for managing libraries and dependencies in .NET applications. Below is a brief overview of NuGet, its features, and how it integrates with the .NET ecosystem.
NuGet Package Manager
Definition
NuGet is the official package manager for .NET. It provides a way to create, share, and consume packages of reusable code. Packages can contain compiled code (DLLs), scripts, and other content needed for a project.
Key Features
Package Creation: Developers can create their own NuGet packages to share libraries or tools with others. A package typically includes compiled code, metadata, and dependencies.
Package Consumption: NuGet allows developers to easily add, update, and remove packages in their projects. This simplifies the process of managing dependencies.
Versioning: NuGet supports versioning of packages, allowing developers to specify which version of a package they want to use. This helps in maintaining compatibility and stability in applications.
Dependency Management: NuGet automatically resolves and installs dependencies for packages, ensuring that all required libraries are available for the project.
Integration with IDEs: NuGet is integrated into popular IDEs like Visual Studio and Visual Studio Code, providing a user-friendly interface for managing packages.
NuGet Gallery: The official NuGet Gallery (https://www.nuget.org/) is a public repository where developers can publish and share their packages. It also allows users to search for and download packages.
Common Commands
NuGet can be used via the command line or through the Package Manager Console in Visual Studio. Here are some common commands:
Install a Package:
1
dotnet add package <PackageName>
Update a Package:
1
dotnet update package <PackageName>
Remove a Package:
1
dotnet remove package <PackageName>
List Installed Packages:
1
dotnet list package
Package Configuration: Packages are typically configured in the project file (e.g.,
.csproj
for C# projects) or in apackages.config
file. The project file includes references to the packages used in the project, along with their versions.
Importing packages/files into your own file
In C#, importing packages and calling specific functions can be done for both custom files (like your own classes) and NuGet packages. Below, I’ll explain how to do this for both scenarios.
- Importing Custom Files
Step 1: Create a Custom Class
First, create a custom class in a separate file. For example, create a file named
MathUtilities.cs
:Step 2: Import the Namespace
In your main program file (e.g.,
Program.cs
), you need to import the namespace where your custom class is defined:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Program.cs using System; using MyUtilities; // Import the namespace class Program { static void Main() { int sum = MathUtilities.Add(5, 3); // Call the Add method int difference = MathUtilities.Subtract(5, 3); // Call the Subtract method Console.WriteLine($"Sum: {sum}"); // Output: Sum: 8 Console.WriteLine($"Difference: {difference}"); // Output: Difference: 2 } }
- Importing NuGet Packages
Step 1: Install the NuGet Package
You can install a NuGet package using the command line or through Visual Studio. For example, to install the
Newtonsoft.Json
package, you can use the following command:1
dotnet add package Newtonsoft.Json
Step 2: Import the Namespace
After installing the package, you need to import the namespace associated with the package. For
Newtonsoft.Json
, the namespace isNewtonsoft.Json
.1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
// Program.cs using System; using Newtonsoft.Json; // Import the namespace for the NuGet package class Program { static void Main() { // Create an object to serialize var person = new { Name = "Alice", Age = 30 }; // Serialize the object to a JSON string string json = JsonConvert.SerializeObject(person); // Output the JSON string Console.WriteLine(json); // Output: {"Name":"Alice","Age":30} // Deserialize the JSON string back to an object var deserializedPerson = JsonConvert.DeserializeObject<dynamic>(json); Console.WriteLine($"Name: {deserializedPerson.Name}, Age: {deserializedPerson.Age}"); // Output: Name: Alice, Age: 30 } }