C#Simple Getting Started - Suitable for Beginners

Posted by roneill on Sat, 30 May 2020 18:44:39 +0200

First C#Program

using System;
namespace HelloWorldApplication   // Namespace Declarations
{
    /* Class name is HelloWorld */
    class HelloWorld			  // A class
    {
        /* main function */
        static void Main(string[] args)	
        {
            /* My First C#Program */
            Console.WriteLine("Hello World!");
            Console.ReadKey();
        }
    }
}

C#Program Structure

  • Namespace declaration
  • A class
  • Class method
  • Class attribute
  • A Main method
  • Statements & Expressions
  • Notes

2. Data Types

1. Value types

type describe Range of values default
bool Boolean Value True or False False
byte 8-bit unsigned integer 0 to 255 0
char 16-bit Unicode characters U +0000 to U +ffff '0'
decimal 128-bit exact decimal value, 28-29 significant digits (-7.9 x 1028 to 7.9 x 1028) / 100 to 28 0.0M
double 64-bit double precision floating point (+/-) 5.0 x 10-324 to (+/-) 1.7 x 10308 0.0D
float 32 Bit Single Precision Floating Point -3.4 x 1038 to + 3.4 x 1038 0.0F
int 32-bit signed integer type -2,147,483,648 to 2,147,483,647 0
long 64-bit signed integer type -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 0L
sbyte 8-bit signed integer type -128 to 127 0
short 16-bit signed integer type -32,768 to 32,767 0
uint 32-bit unsigned integer type 0 to 4,294,967,295 0
ulong 64-bit unsigned integer type 0 to 18,446,744,073,709,551,615 0
ushort 16-bit unsigned integer type 0 to 65,535 0

2. Type Conversion

  1. Type conversion is fundamentally type casting, or the conversion of data from one type to another.In C#, type casting has two shapes:
  • Implicit type conversions - These conversions are C#default, secure conversions that do not result in data loss.For example, from a small integer type to a large integer type, from a derived class to a base class.

  • Explicit type conversion - Explicit type conversion, that is, forced type conversion.Explicit conversion requires a cast operator, and a cast causes data loss.

Case:

namespace TypeConversionApplication
{
    class ExplicitConversion
    {
        static void Main(string[] args)
        {
            double d = 5673.74;
            int i;

            // Cast double to int
            i = (int)d;
            Console.WriteLine(i);
            Console.ReadKey();
            
        }
    }
}
Output result: 5673
  1. C#Type Conversion Method
	1. ToBoolean: Convert the type to Boolean if possible.
	2. ToByte: Convert the type to a byte type.
	3. ToChar: Convert the type to a single Unicode character type if possible.
	4. ToDateTime: Converts the type (integer or string type) to a date-time structure.
	5. ToDecimal: Converts a floating point or integer type to a decimal type.
	6. ToDouble: Convert the type to double precision floating point.
	7. ToInt16: Convert the type to a 16-bit integer type.
	8 ToInt32: Convert the type to a 32-bit integer type.
	9 ToInt64: Convert the type to a 64-bit integer type.
	10 ToSbyte: Converts a type to a signed byte type.
	11 ToSingle: Convert the type to a small floating point type.
	12 ToString: Converts a type to a string type.
	13 ToType: Converts a type to a specified type.
	14 ToUInt16: Convert the type to a 16-bit unsigned integer type.
	15 ToUInt32: Convert the type to a 32-bit unsigned integer type.
	16 ToUInt64: Converts a type to a 64-bit unsigned integer type.

case

namespace TypeConversionApplication
{
    class StringConversion
    {
        static void Main(string[] args)
        {
            int i = 75;
            float f = 53.005f;
            double d = 2345.7652;
            bool b = true;

            Console.WriteLine(i.ToString());
            Console.WriteLine(f.ToString());
            Console.WriteLine(d.ToString());
            Console.WriteLine(b.ToString());
            Console.ReadKey();
            
        }
    }
}

Output results:

75
53.005
2345.7652
True

3. Variables

A variable is simply the name of a store that the program operates on.In C#, each variable has a specific type that determines its memory size and layout.Values in the range can be stored in memory and a series of operations can be performed on variables.

We have discussed various data types.The basic value types provided in C#can be roughly divided into the following categories:

type Give an example
Integer type sbyte, byte, short, ushort, int, uint, long, ulong, and char
float float and double
The Decimal Type decimal
Boolean type true or false value, specified value
Empty type Nullable data type

1. Definition of variables

int i, j, k;
char c, ch;
float f, salary;
double d;

2. Variables can also be initialized when defined

int i = 100;

3. Initialization of variables

int d = 3, f = 5;    /* Initialize d and f. */
byte z = 22;         /* Initialize z. */
double pi = 3.14159; /* Declare approximation of pi */
char x = 'x';        /* The value of variable x is'x' */

4. Examples

namespace VariableDefinition
{
    class Program
    {
        static void Main(string[] args)
        {
            short a;
            int b ;
            double c;

            /* Actual Initialization */
            a = 10;
            b = 20;
            c = a + b;
            Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c);
            Console.ReadLine();
        }
    }
}

Output: a = 10, b = 20, c = 30

5. Accept values from users

int num;
num = Convert.ToInt32(Console.ReadLine());

4. Constants

1. Definition

Constants are fixed values that do not change during program execution.Constants can be any basic data type, such as integer constants, floating-point constants, character constants, or string constants, as well as enumeration constants.

Constants can be treated as regular variables, but their values cannot be modified after they are defined.

2. Integer Constants

Integer constants can be decimal, octal, or hexadecimal constants.The prefix specifies the cardinality: 0x or 0X for hexadecimal, 0 for octal, and no prefix for decimal.

Integer constants can also have suffixes, which can be a combination of U and L, where U and L represent unsigned and long, respectively.Suffixes can be uppercase or lowercase, and multiple suffixes can be combined in any order.

Here are some examples of integer constants:

212         /* legitimate */
215u        /* legitimate */
0xFeeL      /* legitimate */
078         /* Illegal: 8 is not an octal number */
032UU       /* Illegal: Cannot repeat suffix */

The following are examples of various types of integer constants:

85         /* Decimal system */
0213       /* Octal number system */
0x4b       /* Hexadecimal */
30         /* int */
30u        /* Unsigned int */
30l        /* long */
30ul       /* Unsigned long */

3. Floating-point constants

A floating-point constant consists of an integer part, a decimal point, a decimal part, and an exponential part.You can represent floating-point constants in decimal or exponential form.

Here are some examples of floating-point constants:

3.14159       /* legitimate */
314159E-5L    /* legitimate */
510E          /* Illegal: Incomplete Index */
210f          /* Illegal: no decimal or exponent */
.e55          /* Illegal: missing integer or decimal */

When expressed as a decimal, you must include a decimal point, an exponent, or both.When expressed in exponential form, you must include the integer part, the decimal part, or both.Signed exponents are expressed in E or E.

4. Character constants

Escape Sequence Meaning
\ \character
' 'Character
" "Characters
? ? Character
\a Alert or bell
\b Backspace
\f Form feed
\n Line Break (Newline)
\r Enter
\t Horizontal tab
\v Vertical tab
\ooo One-to-three octal numbers
\xhh . . . Hexadecimal number of one or more digits

5. Define constants

using System;

public class ConstTest 
{
    class SampleClass
    {
        public int x;
        public int y;
        public const int c1 = 5;
        public const int c2 = c1 + 5;

        public SampleClass(int p1, int p2) 
        {
            x = p1; 
            y = p2;
        }
    }

    static void Main()
    {
        SampleClass mC = new SampleClass(11, 22);
        Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y);
        Console.WriteLine("c1 = {0}, c2 = {1}", 
                          SampleClass.c1, SampleClass.c2);
    }
}

Result

x = 11, y = 22
c1 = 5, c2 = 10

5. Operators

1. Arithmetic Operators

operator describe Example
+ Add two operands together A + B will get 30
- Subtract the second operand from the first A - B will get -10
* Multiply two operands A * B will get 200
/ Molecule divided by denominator B / A will get 2
% Modular operator, remainder after integer division B% A will get 0
++ Self-incrementing operator, integer value increment 1 A++ will get 11
-- Self-decreasing operator, integer value reduced by 1 A--You'll get 9

2. Relational Operators

operator describe Example
== Check that the values of the two operands are equal, and if they are equal, the condition is true. (A == B) is not true.
!= Check that the values of the two operands are equal, and if they are not, the condition is true. (A!= B) True.
> Check if the value of the left operand is greater than the value of the right operand, and if so, the condition is true. (A > B) is not true.
< Check if the value of the left operand is less than the value of the right operand, and if so, the condition is true. (A < B) is true.
>= Check if the value of the left operand is greater than or equal to the value of the right operand, and if so, the condition is true. (A >= B) is not true.
<= Check if the value of the left operand is less than or equal to the value of the right operand, and if so, the condition is true. (A <= B) is true.
using System;

class Program
{
  static void Main(string[] args)
  {
      int a = 21;
      int b = 10;
      
      if (a == b)
      {
          Console.WriteLine("Line 1 - a Be equal to b");
      }
      else
      {
          Console.WriteLine("Line 1 - a Not equal to b");
      }
      if (a < b)
      {
          Console.WriteLine("Line 2 - a less than b");
      }
      else
      {
          Console.WriteLine("Line 2 - a Not less than b");
      }
      if (a > b)
      {
          Console.WriteLine("Line 3 - a greater than b");
      }
      else
      {
          Console.WriteLine("Line 3 - a Not greater than b");
      }
      /* Change the values of a and b */
      a = 5;
      b = 20;
      if (a <= b)
      {
         Console.WriteLine("Line 4 - a Less than or equal to b");
      }
      if (b >= a)
      {
         Console.WriteLine("Line 5 - b Greater than or equal to a");
      }
  }
}

Output Results

Line 1 - a does not equal b
 Line 2 - a not less than b
 Line 3 - a is greater than b
 Line 4 - a is less than or equal to b
 Line 5 - b greater than or equal to a

3. Logical Operators

operator describe Example
&& They are called logical and operators.If both operands are non-zero, the condition is true. (A && B) is false.
! It is called a logical nonoperator.Used to reverse the logical state of an operand.If the condition is true, the logical nonoperator will make it false. (A && B) is true.

4. Bit Operators (*)

operator describe Example
& If both operands exist, the binary AND operator copies one bit into the result. (A & B) will get 12, 0000 1100
If present in any operand, the binary OR operator copies one bit into the result.
^ If it exists in one of the operands but not in both, the binary XOR operator copies one bit into the result. (A ^ B) will get 49, which is 0011 0001
~ The bitwise negation operator is a unary operator with the effect of flipping bits, where 0 becomes 1 and 1 becomes 0, including symbol bits. (~A) yields -61, which is 1100011, a complement form of signed binary numbers.
<< Binary left shift operator.The value of the left operand moves to the left the number of digits specified by the right operand. A << 2 will get 240, 111 0000
>> Binary right shift operator.The value of the left operand moves to the right the number of digits specified by the right operand. A >> 2 will get 15, 0000 1111

5. Assignment Operators

operator describe Example
= A simple assignment operator that assigns the value of the right operand to the left operand C = A + B assigns a value of A + B to C
+= Addition and assignment operator assigns the result of the right plus left operands to the left operand C += A equals C = C + A
-= Subtraction and assignment operator assigns the result of subtracting the left operand from the right operand to the left operand C -= A equals C = C - A
*= Multiplication and assignment operator assigns the result of multiplying the right operand by the left operand to the left operand C *= A equals C = C * A
/= Divide and assign operators, assign the result of dividing the left operand by the right operand to the left operand C /= A equals C = C / A
%= Evaluate the modulus and assign the operator. Evaluate the modulus of two operands to the left operand C%= A equals C = C% A
<<= Move left with assignment operator C <<= 2 equals C = C << 2
>>= Move Right with Assignment Operator C >>= 2 equals C = C >> 2
&= Bitwise And Assignment Operator C &= 2 equals C = C & 2
^= Bitwise XOR and Assignment Operator C ^= 2 equals C = C ^ 2
= Bitwise Or Assignment Operator

6. Other Operators

operator describe Example
sizeof() Returns the size of the data type. sizeof(int), returns 4.
typeof() Returns the type of class. typeof(StreamReader);
& Returns the address of the variable. &a; The actual address of the variable is obtained.
* A pointer to a variable. *a; will point to a variable.
? : Conditional expression X if the condition is true: otherwise Y
is Determine whether the object is of a certain type. If (Ford is Car) //Check if Ford is an object of the Car class.
as A cast does not throw an exception even if it fails. Object obj = new StringReader("Hello"); StringReader r = obj as StringReader;

7. Operator Priority

category operator Binding
Suffix () [] -> . ++ - - From left to right
Monary + - ! ~ ++ - - (type)* & sizeof From right to left
Multiplication and Division * / % From left to right
Addition and Subtraction + - From left to right
Displacement << >> From left to right
relationship < <= > >= From left to right
Equal == != From left to right
Bits and AND & From left to right
Bitwise XOR ^ From left to right
Bit or OR
Logic and AND && From left to right
Logic or OR
condition ?: From right to left
assignment = += -= *= /= %=>>= <<= &= ^= =
comma , From left to right

6. Judgment

1. Judgment statements

Sentence describe
if statement An if statement consists of a Boolean expression followed by one or more statements.
if...else statement An if statement can be followed by an optional else statement that is executed when the Boolean expression is false.
Nested if statement You can use another if or else if statement within one if or else statement.
switch statement A switch statement allows you to test when a variable is equal to more than one value.
Nested switch statement You can use another switch statement within one switch statement.
Case 1 - if statement
using System;

namespace DecisionMaking
{
    
    class Program
    {
        static void Main(string[] args)
        {
            /* Local variable definition */
            int a = 10;

            /* Checking Boolean Conditions with an if statement */
            if (a < 20)
            {
                /* If the condition is true, output the following statement */
                Console.WriteLine("a Less than 20");
            }
            Console.WriteLine("a The value of is {0}", a);
            Console.ReadLine();
        }
    }
}

a Less than 20
a Has a value of 10
Case 2 - if...else statement
using System;

namespace DecisionMaking
{
    
    class Program
    {
        static void Main(string[] args)
        {

            /* Local variable definition */
            int a = 100;

            /* Check Boolean Conditions */
            if (a < 20)
            {
                /* If the condition is true, output the following statement */
                Console.WriteLine("a Less than 20");
            }
            else
            {
                /* If the condition is false, output the following statement */
                Console.WriteLine("a More than 20");
            }
            Console.WriteLine("a The value of is {0}", a);
            Console.ReadLine();
        }
    }
}
a More than 20
a The value is 100
Case 3 - Nested if statement
using System;

namespace DecisionMaking
{
    
    class Program
    {
        static void Main(string[] args)
        {

            //*Local variable definitions*/
            int a = 100;
            int b = 200;

            /* Check Boolean Conditions */
            if (a == 100)
            {
                /* If the condition is true, check the following conditions */
                if (b == 200)
                {
                    /* If the condition is true, output the following statement */
                    Console.WriteLine("a The value is 100, and b The value is 200");
                }
            }
            Console.WriteLine("a The exact value is {0}", a);
            Console.WriteLine("b The exact value is {0}", b);
            Console.ReadLine();
        }
    }
}

//When the above code is compiled and executed, it produces the following results:

a The value is 100, and b The value is 200
a The exact value is 100
b The exact value is 200
Case 4 - switch statement
using System;

namespace DecisionMaking
{
    
    class Program
    {
        static void Main(string[] args)
        {
            /* Local variable definition */
            char grade = 'B';

            switch (grade)
            {
                case 'A':
                    Console.WriteLine("Excellent!");
                    break;
                case 'B':
                case 'C':
                    Console.WriteLine("Do well");
                    break;
                case 'D':
                    Console.WriteLine("You have passed");
                    break;
                case 'F':
                    Console.WriteLine("Better try again");
                    break;
                default:
                    Console.WriteLine("Invalid results");
                    break;
            }
            Console.WriteLine("Your results are {0}", grade);
            Console.ReadLine();
        }
    }
}
//When the above code is compiled and executed, it produces the following results:

//Do well
//Your results are 
Case 5 - Nested switch statement
using System;

namespace DecisionMaking
{
    
    class Program
    {
        static void Main(string[] args)
        {
            int a = 100;
            int b = 200;

            switch (a)
            {
                case 100:
                    Console.WriteLine("This is external switch Part of");
                    switch (b)
                    {
                        case 200:
                        Console.WriteLine("This is internal switch Part of");
                        break;
                    }
                    break;
            }
            Console.WriteLine("a The exact value is {0}", a);
            Console.WriteLine("b The exact value is {0}", b);
            Console.ReadLine();
        }
    }
} 
//When the above code is compiled and executed, it produces the following results:

//This is part of the external switch
//This is part of the internal switch
a The exact value is 100
b The exact value is 200

2.?: Operator

The following two sentences of code are the same

1. if(a>b){max = a;}else{max=b;}
2. max = a>b?a:b;

7. Circulation

1. Cycle type

Cycle type describe
while loop Repeats a statement or group of statements when a given condition is true.It tests the condition before executing the loop body.
for/foreach loop Execute a sequence of statements multiple times to simplify the code for managing circular variables.
do...while loop It is similar to a while statement except that it tests the condition at the end of the loop body.
Nested loop You can use one or more loops within a while, for, or do..while loop.

2. Loop control statements

Control statement describe
break statement Terminates a loop or switch statement, and the program flow continues to execute the next statement that follows the loop or switch.
continue statement Causes a loop to skip the rest of the body and immediately restart the test condition.
Case 1 - while Loop
using System;

namespace Loops
{
    
    class Program
    {
        static void Main(string[] args)
        {
            /* Local variable definition */
            int a = 10;

            /* while Loop Execution */
            while (a < 20)
            {
                Console.WriteLine("a Value of: {0}", a);
                a++;
            }
            Console.ReadLine();
        }
    }
} 
//When the above code is compiled and executed, it produces the following results:

a Value of: 10
a Value of: 11
a Value of: 12
a Value of: 13
a Value of: 14
a Value of: 15
a Value of: 16
a Value of: 17
a Value of: 18
a Value of: 19
Case 2 - for cycle
using System;

namespace Loops
{
    
    class Program
    {
        static void Main(string[] args)
        {
            /* for Loop Execution */
            for (int a = 10; a < 20; a = a + 1)
            {
                Console.WriteLine("a Value of: {0}", a);
            }
            Console.ReadLine();
        }
    }
} 
//When the above code is compiled and executed, it produces the following results:

a Value of: 10
a Value of: 11
a Value of: 12
a Value of: 13
a Value of: 14
a Value of: 15
a Value of: 16
a Value of: 17
a Value of: 18
a Value of: 19
Case 3 - foreach cycle
class ForEachTest
{
    static void Main(string[] args)
    {
        int[] fibarray = new int[] { 0, 1, 1, 2, 3, 5, 8, 13 };
        foreach (int element in fibarray)
        {
            System.Console.WriteLine(element);
        }
        System.Console.WriteLine();


        // Like foreach loop
        for (int i = 0; i < fibarray.Length; i++)
        {
            System.Console.WriteLine(fibarray[i]);
        }
        System.Console.WriteLine();


        // Sets the calculator for the elements in the collection
        int count = 0;
        foreach (int element in fibarray)
        {
            count += 1;
            System.Console.WriteLine("Element #{0}: {1}", count, element);
        }
        System.Console.WriteLine("Number of elements in the array: {0}", count);
    }
}
//The output is:

0
1
1
2
3
5
8
13

0
1
1
2
3
5
8
13

Element #1: 0
Element #2: 1
Element #3: 1
Element #4: 2
Element #5: 3
Element #6: 5
Element #7: 8
Element #8: 13
Number of elements in the array: 8
Case 4 - do...while loop
using System;

namespace Loops
{
    
    class Program
    {
        static void Main(string[] args)
        {
            /* Local variable definition */
            int a = 10;

            /* do Loop Execution */
            do
            {
               Console.WriteLine("a Value of: {0}", a);
                a = a + 1;
            } while (a < 20);

            Console.ReadLine();
        }
    }
} 
//When the above code is compiled and executed, it produces the following results:

a Value of: 10
a Value of: 11
a Value of: 12
a Value of: 13
a Value of: 14
a Value of: 15
a Value of: 16
a Value of: 17
a Value of: 18
a Value of: 19
Case 5 - Nested Loops
using System;

namespace Loops
{
    
   class Program
   {
      static void Main(string[] args)
      {
         /* Local variable definition */
         int i, j;

         for (i = 2; i < 100; i++)
         {
            for (j = 2; j <= (i / j); j++)
               if ((i % j) == 0) break; // If found, it is not a prime number
            if (j > (i / j)) 
               Console.WriteLine("{0} Is a prime number", i);
         }

         Console.ReadLine();
      }
   }
} 
//When the above code is compiled and executed, it produces the following results:

2 Is a prime number
3 Is a prime number
5 Is a prime number
7 Is a prime number
11 Is a prime number
13 Is a prime number
17 Is a prime number
19 Is a prime number
23 Is a prime number
29 Is a prime number
31 Is a prime number
37 Is a prime number
41 Is a prime number
43 Is a prime number
47 Is a prime number
53 Is a prime number
59 Is a prime number
61 Is a prime number
67 Is a prime number
71 Is a prime number
73 Is a prime number
79 Is a prime number
83 Is a prime number
89 Is a prime number
97 Is a prime number

8. Arrays

1. Definition

An array is an ordered collection of fixed sizes that store elements of the same type.Arrays are collections used to store data and are generally considered a collection of variables of the same type.

Declaring array variables does not declare number0, number1,..., number99 as separate variables, but rather a variable like numbers, which is then represented by numbers[0], numbers[1],..., numbers[99].A specified element in an array is accessed through an index.

All arrays consist of contiguous memory locations.The lowest address corresponds to the first element, and the highest address corresponds to the last element.

2. Declarations of arrays

double[] balance;

3. Initialization of arrays

double[] balance = new double[10];

4. Assignment of arrays

You can assign a single array element by using an index number, such as:

double[] balance = new double[10];
balance[0] = 4500.0;

You can assign values to an array while declaring it, for example:

double[] balance = { 2340.0, 4523.69, 3421.0};

You can also create and initialize an array, such as:

int [] marks = new int[5]  { 99,  98, 92, 97, 95};

In these cases, you can also omit the size of the array, such as:

int [] marks = new int[]  { 99,  98, 92, 97, 95};

You can also assign an array variable to another target array variable.In this case, the target and source point to the same memory location:

int [] marks = new int[]  { 99,  98, 92, 97, 95};
int[] score = marks;

5. Access to arrays

Elements are accessed through indexed array names.This is achieved by placing the element's index in square brackets after the array name.For example:

double salary = balance[9];

The following is an example of using the three concepts mentioned above, namely, declaration, assignment, and access array:

using System;
namespace ArrayApplication
{
   class MyArray
   {
      static void Main(string[] args)
      {
         int []  n = new int[10]; /* n Is an array with 10 integers */
         int i,j;


         /* Initialize elements in array n */         
         for ( i = 0; i < 10; i++ )
         {
            n[ i ] = i + 100;
         }

         /* Output the value of each array element */
         for (j = 0; j < 10; j++ )
         {
            Console.WriteLine("Element[{0}] = {1}", j, n[j]);
         }
         Console.ReadKey();
      }
   }
}
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109

Topics: Programming less Attribute REST calculator