Basic Concepts of C#

Mannan Ul Haq
0

C# Syntax:

Let's begin by analyzing and breaking down a simple C# code snippet:

using System;

namespace MyFirstApplication
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("Hello World!");
        }
    }
}

Explanation of the code:

Line 1: `using System;` is a using directive that allows us to work with classes and functionality defined in the `System` namespace. The `System` namespace provides essential features for C# programs, including input/output and basic data types.

Line 2: A blank line. C# ignores white space. However, multiple lines makes the code more readable.

Line 3: The keyword `namespace` is used to define a new namespace called `MyFirstApplication`. Namespaces are used to organize and group related code together.

Line 5: The keyword `class` is used to define a new class called `Program`. In C#, everything is wrapped inside classes, and `Program` is our starting point. The `{}` curly brackets enclose the body of the `Program` class, where the actual code execution takes place.

Line 7: The `static` keyword means that the `Main` method is a class-level method and can be called without creating an instance of the `Program` class. The `void` keyword indicates that the `Main` method does not return any value. The `Main` method is the entry point of the program. It is the first method that gets executed when the program starts running. The `{}` curly brackets enclose the body of the `Main` method, where the actual code execution takes place.

Line 9: `Console.WriteLine("Hello World!");` is a statement that uses the `Console` class from the `System` namespace to print "Hello World!" to the console.

Note: Every C# statement ends with a semicolon ;.


Output in C#:

In C#, the `Console.WriteLine()` and `Console.Write()` methods are used to display output to the console window. These methods belong to the `Console` class, which is part of the `System` namespace. They are fundamental for interacting with users, providing feedback, and displaying information in C# console applications.

1. `Console.WriteLine()`:

The `Console.WriteLine()` method is used to print text or data followed by a new line in the console window. It automatically adds a newline character after the output, so each subsequent output appears on a new line.

Example:

Console.WriteLine("Hello World!");
Console.WriteLine("Welcome to CodeTechMentor!");

Output:

Hello World!
Welcome to CodeTechMentor!

2. `Console.Write()`:

The `Console.Write()` method is similar to `Console.WriteLine()`, but it does not add a newline character after the output. As a result, consecutive outputs appear on the same line.

Example:

Console.Write("Hello, ");
Console.Write("this is ");
Console.Write("a single line output.");

Output:

Hello, this is a single line output.


Comments in C#:

In C#, comments are used to add explanatory or descriptive text within the source code that is ignored by the compiler. Comments serve as notes for developers and have no impact on the execution of the program. There are two types of comments in C#:

Single-line comments:

Single-line comments start with `//` and continue until the end of the line. Anything following `//` on the same line is considered a comment.

// This is a single-line comment.
Console.WriteLine("Hello World!"); // This line also contains a single-line comment.

Multi-line comments:

Multi-line comments begin with `/*` and end with `*/`. They can span multiple lines and are often used for longer explanations or temporarily disabling blocks of code.

/* This is a multi-line comment.
   It can span across multiple lines.
   Console.WriteLine("This line is commented out.");
*/
Console.WriteLine("Hello World!");


Data Types in C#:

In C#, data types specify the type of data that can be stored in a variable. Some common built-in data types in C# include:

  • `int`: Used for storing integers (whole numbers).
  • `float` and `double`: Used for storing floating-point numbers (decimal numbers).
  • `char`: Used for storing individual characters.
  • `bool`: Used for storing boolean values (`true` or `false`).
  • `string`: Used for storing a sequence of characters.

Here's a quick reference table for the size (in bytes) of some common data types in C#:

Data Type

Size (in bytes)

bool

1

char

2

int

4

long

8

float

4

double

8




Variables in C#:

A variable is a named storage location that holds a value of a specific data type. Variables need to be declared before they can be used. The syntax for declaring a variable is: `data_type variable_name = value;`.

int Num = 10;
Console.WriteLine(Num);

In this example, we declare a variable called `Num` of type `int` and assign it the value `10`. Later, we use `Console.WriteLine()` to display the value of `Num`, which will output `10` to the console.


You can also declare a variable without assigning the value immediately and assign the value later:

int Num;
Num = 20;
Console.WriteLine(Num);


Please note that in C#, if you assign a new value to a variable that already has a value, the previous value will be overwritten:

int x = 5; // x is assigned the value 5
x = 10;    // The value of x is updated to 10
Console.WriteLine(x); // Outputs 10

Other Data Types in C#:

C# supports a variety of data types to accommodate different types of data. Here's a demonstration of different data types in C#:

int Num = 10;               // Integer (whole number without decimals)
double Float = 12.66;    // Floating-point number (with decimals)
char Letter = 'A';         // Character
string Text = "Hello";     // String (text)
bool Boolean = true;       // Boolean (true or false)

These data types allow you to work with a wide range of data in your C# programs.

NOTE: The float and double data types have the ability to store fractional numbers. It is important to remember that when assigning values to these data types, you must use an "F" suffix for floats and you can also use a "D" suffix for doubles but it is not compulsory. (alert-success)

 

float myFloat = 3.14F; // Note: The "F" suffix indicates a float value
Console.WriteLine(myFloat);

double myDouble = 123.456D;
Console.WriteLine(myDouble);



Identifiers in C#:

Identifiers are names given to variables, functions, or any other user-defined entities in C#. They help identify and refer to these entities within the code. Some rules for naming identifiers in C# are:

  • Identifiers can include letters, digits, and underscores (_).
  • The first character must be a letter or an underscore.
  • Identifiers are case-sensitive (`age` and `Age` are different).
  • Names cannot contain whitespaces or special characters like !, #, %, etc.
  • Reserved keywords (e.g., `int`, `float`) cannot be used as identifiers.


White-Space in C#:

In C#, whitespace refers to spaces, tabs, and newlines used for formatting and separation of code elements. Whitespace is generally ignored by the compiler and serves the purpose of enhancing code readability. Here are some examples of Whitespace:


Whitespace Explanation   Representation
New Line     To Insert a new Line   \n
Tab     To Insert a Tab   \t
Space     To Insert a Space   Empty Space
Double Quote     To Insert a Double Quote Character   \"
Backslash     To Insert a Backslash Character   \\


The use of whitespace improves the organization and readability of your code.


Displaying Variables in C#:

Using Console.WriteLine():

In C#, the `+` sign is used for concatenating strings and variables to create a single combined string. When you use the `+` sign to concatenate a variable with a string, C# automatically converts the variable to its string representation before combining it with the other string.

Example:

string name = "John";
int age = 30;

Console.WriteLine("My name is " + name + " and I am " + age + " years old.");

Output:

My name is John and I am 30 years old.

Using Console.Write():

The Console.Write() method is similar to Console.WriteLine(), but it does not add a newline character after the output. Consecutive outputs will appear on the same line.

int x = 10;
int y = 5;

Console.Write("The value of x is: ");
Console.WriteLine(x);
Console.Write("The value of y is: ");
Console.WriteLine(y);

Output: 

The value of x is: 10
The value of y is: 5


Type Conversion in C#:

Type conversion, also known as type casting, is the process of converting one data type into another in C#. C# supports two types of type conversions: Implicit Conversion and Explicit Conversion.

1. Implicit Conversion (Automatic Conversion):

Implicit conversion occurs when the compiler automatically converts a smaller data type into larger data tpe (char -> int -> long -> float -> double), ensuring that no data loss or precision loss occurs. This conversion is considered safe and doesn't require any explicit casting operator.

Example of Implicit Conversion:

int myInt = 10;
double myDouble = myInt; // Implicitly converting int to double

In this example, the `myInt` variable of type `int` is implicitly converted into a `double`. Since there is no loss of data or precision (integers can be accurately represented as floating-point numbers), the conversion is performed automatically.

2. Explicit Conversion (Type Casting or Type Conversion Methods):

Explicit conversion, also known as type casting, occurs when you manually convert larger data type into smaller (double -> float -> long -> int -> char), using casting operators or type conversion methods. Explicit conversions are necessary when there may be a potential loss of data or precision during the conversion.

Example of Explicit Conversion:

double myDouble = 3.14;
int myInt = (int)myDouble; // Explicitly casting double to int

Type Conversion Methods:

C# provides various methods to perform explicit type conversions between different data types. Here are some commonly used type conversion methods:

1. `Convert.ToBoolean`:

This method converts a value to a boolean (true or false) data type. The input value can be of any compatible data type.

Example:

int intValue = 1;
bool boolValue = Convert.ToBoolean(intValue); // Converts the integer value 1 to true

2. `Convert.ToDouble`:

This method converts a value to a double-precision floating-point number (double). The input value can be of any compatible data type.

Example:

string doubleString = "3.14";
double doubleValue = Convert.ToDouble(doubleString); // Converts the string "3.14" to a double value 3.14

3. `Convert.ToString`:

This method converts a value to its string representation. The input value can be of any compatible data type.

Example:

int intValue = 42;
string stringValue = Convert.ToString(intValue); // Converts the integer value 42 to the string "42"

4. `Convert.ToSingle` (float):

This method converts a value to a single-precision floating-point number (float). The input value can be of any compatible data type.

Example:

double doubleValue = 3.14;
float floatValue = Convert.ToSingle(doubleValue); // Converts the double value 3.14 to the float value 3.14F

5. `Convert.ToInt32` (int):

This method converts a value to a 32-bit signed integer (int). The input value can be of any compatible data type.

Example:

double doubleValue = 3.14;
int intValue = Convert.ToInt32(doubleValue); // Converts the double value 3.14 to the integer value 3

Remember to choose the appropriate method based on the data types involved in the conversion. Using these built-in methods ensures that the conversion is handled safely, and it helps maintain data integrity in your code. (alert-success)


User Input in C#:

In C#, `Console.ReadLine()` is a method used to obtain user input from the console. It reads the entire line of text entered by the user until they press the Enter key and returns the input as a string. Let's explore how to use `Console.ReadLine()` to get user input and handle numeric input correctly:

Example:

// Type your username and press enter
Console.WriteLine("Enter username:");

// Create a string variable and get user input from the keyboard and store it in the variable
string userName = Console.ReadLine();

// Print the value of the variable (userName), which will display the input value
Console.WriteLine("Username is: " + userName);

In the above example, the program prompts the user to enter their username. The input provided by the user is read using `Console.ReadLine()`, and it is stored in the `userName` variable, which is of type `string`. Since `Console.ReadLine()` returns a string, it can be directly assigned to the `userName` variable.

User Input and Numbers:

When you want to get numeric input from the user, you need to be aware that `Console.ReadLine()` always returns a string. Therefore, you cannot directly store the result into numeric data types like `int`, `double`, etc. Attempting to do so will cause a compilation error with the message "Cannot implicitly convert type 'string' to 'int'".

To handle numeric input correctly, you can use explicit type conversion methods to convert the user input from string to the desired numeric data type. Here's an example of getting the user's age as an integer:

Console.WriteLine("Enter your age:");

// Use Convert.ToInt32() to convert the user input (string) to an integer
int age = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Your age is: " + age);

In this example, the program prompts the user to enter their age. The input provided by the user is read using `Console.ReadLine()`, and then `Convert.ToInt32()` is used to convert the input from a string to an integer, which is stored in the `age` variable. Now, you can work with the user's age as an integer and perform any desired calculations or operations.

Tags

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !