Last Updated:

C sharp syntax

C Sharp or C# is a programming language for creating application computer programs for operating systems of the Microsoft family. The language was released in 2001 by several developers led by Anders Heilsberg and Scott Wiltaumot. Applications developed in C# target the Microsoft .NET Framework. To date, a huge number of class libraries have been created for C#.

Language is a descendant of the C language and is the most perfect creation of the C-like language family. It incorporates all the best of C and C++, the syntax is very similar to Java, and also has its own characteristics.

C# itself is an object-oriented programming language. It combines strong and dynamic typing. The language supports all OOP paradigms:

  • inheritance
  • polymorphism
  • Encapsulation
  • Abstraction.

 

It supports a huge set of data structures that allow a flexible storage system for various data. A huge advantage of the language is the automated cleaning of memory - the removal of references to objects triggers the mechanism for deleting the objects themselves on the heap, which avoids memory leaks. But that's not what this article is about. We will consider the very basics. Namely, the syntax of the C# language.

 

What is the syntax of a language?

 

The syntax of a programming language is a stack of rules that form a single system for writing programs. Writing code is carried out according to strict compliance with the rules for writing programs in a particular language. That is, there is a certain system for writing programs, deviation from which will not allow the processor to execute the algorithm and will lead to an error indication.

For example, a Russian person understands russian, a Chinese person understands Chinese, an Englishman understands English. If an Englishman is told something in Chinese or just a set of letters, then he will not be able to understand the information coming into his brain.

The program must write in accordance with the rules of program structure, subroutines, writing arbitrary names, using limited sets of operators and reserved words. The C# compiler understands only syntactically correctly written commands. Otherwise, it will throw a syntax error.

Now it's time to get acquainted with the syntax of C#, which incorporates all the features of the syntax of C, like all C-like languages. We will not consider the mechanics of the work of certain language constructions. But let's just analyze the rules for their description.

Ids

 

Identifiers are all arbitrary names that perform the function of referencing memory. These are the names of variables, functions, objects, classes, arrays, and other structures. Identifier names are issued according to certain rules:

  • The name can begin with an underscore "_".
  • The name can begin with a capital letter and a lowercase letter — C# is a case-sensitive language. If you create a second variable with the same name, but there is at least one letter in the string that differs in case, then these are already two different variables.

Example: the names car and car are two identical variables; car and Car — different variables are created.

Identifier declarations are not valid in the following cases:

  1. A name cannot begin with a number.
  2. A language keyword cannot be used as an identifier—only if the keyword is preceded by the @ symbol.
  3. The name cannot be longer than 511 characters.

Examples of syntactically correct identifiers are price, size, _size_of_box, sizeOfBox, SIZEOFBox, _price, price12, _@void (the @ symbol before the keyword makes an identifier out of it), identifier (C# supports Unicode).

Examples of syntactically incorrect identifiers are: 12price, int(keyword), void(keyword), 12444_hellO.

Example: Identifiers for variables:

// Correct
int digit;
float _Digit;
double digital;
string arbitrary_name;
string@string; // @ keyword

//Incorrect identifiers
int89digit;
int integer; // keyword
int Object; // keyword

Keywords of the C language #

 

Keywords are the default language identifiers and cannot be used when declaring memory references (variables, arrays, etc.). These are reserved words that have a special syntactic meaning in the language. For example, a keyword marks loops, functions, delegates, events —special language constructs.

There are two kinds of reserved words in C#—general and contextual. The first type is used only as keywords, the second type has limitations and is used only in a certain context. Once again, it is worth mentioning that keywords cannot be used as identifiers if the @ symbol is placed in front of it.

C# provides the following common keywords by default:

  • abstract,
  • as,
  • base,
  • bool,
  • break,
  • byte,
  • case,
  • catch,
  • char,
  • checked,
  • class,
  • const,
  • continue,
  • decimal,
  • default,
  • delegate,
  • do,
  • double,
  • else,
  • enum,
  • event,
  • explicit,
  • external
  • false,
  • finally,
  • fixed,
  • float,
  • for,
  • foreach,
  • goto,
  • if,
  • implicit,
  • protected,
  • public,
  • readonly,
  • ref,
  • return,
  • sbyte,
  • sealed,
  • short,
  • sizeof,
  • stackalloc,
  • static,
  • string,
  • struct,
  • switch,
  • this,
  • throw,
  • true,
  • try,
  • typeof,
  • uint,
  • ulong,
  • unchecked,
  • unsafe,
  • ushort,
  • using,
  • virtual,
  • void,
  • volatile,
  • while,
  • params,
  • private.

The list of contextual reserved words includes:

  • remove,
  • select,
  • set,
  • value,
  • global,
  • group,
  • into,
  • join,
  • add,
  • dynamic,
  • from,
  • get,
  • yield,
  • where.

Literals in the C language #

 

Literals are some kinds of data in a language. These are the values that are processed by language operators, assigned to variables, and returned as a result of processing. Any program is the receipt of the initial values of literals, their processing and the issuance of a ready-made result, which is expressed by these very literals.

C# literals are of the following types:

  1. Decimal: 1, 2, 34, 1289, 444, 53454, 21...;
  2. Шестнадцатиричные: 0*E5, 0*F2, A, F, F8…;
  3. Floating-point: 1.54, 234.54, 4.3...;
  4. Characters bordered by single quotation marks: 'a', 'v', 'r', 'D', 'A', 'F', '2', '0' and other Unicode characters;
  5. Lines framed in paired quotation marks: "My name is Daniel", "Hello everybody!", "how long?";
  6. Escape characters: \u(and Unicode character), \n, \t, \r, \f, \\, and others. Used to edit the output of strings on the screen.

Variables

A variable is a reference to an area of memory where literals of a particular type are stored. A variable name is an identifier that can have an arbitrary set of characters according to the rules of C# syntax. The language has both strong and dynamic typing. Variables can be of a certain type or without it.

Declaring a typed variable begins by setting its type: int, string, boolean, etc. Then the identifier is written.

Example:

int num; declared a variable of type int with the identifier num, in which you can save the value only of type int
float num_float;
char letter;
string word;
var some_var; declaring a variable without explicitly specifying its type

Initializing a variable is assigning it a value (literal) of the type in which it is declared. Variables can be initialized when declared or dynamically at run time. In the example above, variables were declared without initialization. Now let's look at an example of declaring variables with initialization.

Example:

int digit = 24; Assigning an integer literal to a variable when declaring
it string name="Fred";
char some_symbol = «s»;

declaring and then initializing in code

int d; a simple declaration of an integer variable
d = 349; assignment (initialization) in program code

You can declare multiple variables of the same type in abbreviated form.

Example:

without initialization

char a, b, v;

with initialization

int f = 5, x = 9, y = 999;

Constants in C #

A constant is an identifier whose value is fixed. That is, the value of the constant is given once and cannot be changed at run time of the program and cannot be assigned a new value. The constant itself consists of the const keyword, type, identifier, and assigned literal.

Example:

declare a constant without initialization

const double digit;

with initialization

const string company_name = «General Motors»;

company_name = «Hello»; error - constant literal cannot be changed and is read-only

Properties of objects can also be a constant. The value of these properties can no longer be changed. An alternative is properties declared with the readonly keyword.

Blocks

A block in C# is a written algorithm in a separate context from the global one. The block is created by the {} operators — the first bracket opens the block, the second closes it. The global context is the Main function block. Within or beyond it, other blocks create a local context. Blocks within functions also have a sublocal context.

Example:

public static void Main(){ // global context (block)
string g = "Hello!"; // global variable

{
string g = "He!"; local context block
}

Console.print(g); error - there is no variable g in the global context and it is within the scope of the global context
}

static int func(){
int x = 6; // local variable in the local context
}

Basic structure of all programs in C #

C# programs consist of classes. The main algorithm runs inside the Main function. Classes are stored in namespaces and inside other classes. Classes contain various data and functions. Classes within themselves can contain other classes. Namespaces can be connected to the main program to access the functionality of various classes. The main program consists of a namespace, a main class with a Main method.

Namespaces and Classes

Example:

namespace System{ // namespace with ID System, which will have a collection of classe classes
Web_Data{ // class within the namespace

}

class System_data{ // another class
app_data{ // class within a class

}
}

}

Program Structure

The skeleton of the program consists of three main structures:

  1. Namespace.
  2. Main class.
  3. The Main method is an instance of the main class and is the block in which the main algorithm is executed.

Example:

using System
using WindowsForms
using WebObjectsLibrary

namespace Some_NS{
// other classes, structures, interfaces, etc.
class can be described here main_program{
//functions, events or delegates of the main algorithm
of public static void Main(){
// are written here

}
}
}

Connecting External Classes and Namespaces

 

Namespaces and classes are connected so that you can use their functionality. When you create a new project in the development environment, the System namespace is automatically connected, in which there are a huge number of classes, structures and interfaces that allow you to interact with the hardware and software of the computer.

In the example of the "Program Structure" section, you can see such lines as using System and the like in the deck itself. This is the connection of external namespaces and class libraries. The uses keyword indicates that a specific namespace or class will be attached to the main program.

When you use a particular class, you do not have to specify each time which namespace it belongs to. It is enough to connect it through the uses keyword and you can access the class through their identifiers.

You can also connect a single class from the namespace in the following way: uses System.DataCollections. Here, DataCollections can be a class, an interface, or an internal namespace. The remaining System classes will not be connected. You can also use aliases to simplify access to namespace instances.

Example:

using WEB = System.Net;
using Directions_Data = System.IO.DirectoryInfo;

You no longer need to write full access to the class to access static methods and properties:

System.IO.DirectoryInfo.some_mehod().

Just enter the name of the identifier:

Directions_Data.some_method().

Main Main Method

The Main method is an instance of the program's main class by default. It is called by default when the program starts. Outside of the Main method, other classes and functions are described. In the Main method, objects are created, data is processed, functions are called, and objects are created. This method can be of two types: a non-objecting value and returning 0 when the program runs successfully.

Example:

example without returning the value
of public static void Main(){ // the method is always static, and the void keyword says that the method does not return
anything // the main algorithm is written here

}

example with a return value

public static int Main(){ // int means that the method returns an integer

return 0; return zero if the code runs without errors
}

C language operators #

 

Operators in C# and in programming in general are the primary literal processing tool. Operators allow you to perform mathematical operations on numerical literals, various operations on text, create conditions for executing a certain code fragment, separate a block of code and much more.

In C#, there are 16 categories of operators:

  1. Arithmetic: +(add), -(subtract), /(divide), *(multiply), %(get the remainder from division). These operators are used to perform arithmetic operations on integers and floating-point numbers.
  2. Concatenation: + (string join). It is used to add two lines in the don: "Hello"+"World" = "HelloWorld".
  3. Logical: &&(true and true = true — "and" operator), || (true = if there is at least one true - the "or" operator), ! (not true = true - the "not" operator). Used in both conditional constructs and simple Boolean expressions, the result is always true or false.
  4. Encrimment, decriment: ++(add 1), —(subtract 1). Used to abbreviate the arithmetic expression x = x+1(++), x = x-1(—).
  5. Assignment: =(assign value) += or -=(abbreviated record of addition or subtraction with assignment), *= or /= (multiplication or division with assignment), %=(assignment of the remainder of division), &=, || =, ^=, >>=, <<=(bitwise assignment operations). They are used to assign data to variables, as well as the results of expressions. The assigned operator is the abbreviated entry x=x+number, the same as x+=number.
  6. Bitwise operators: &(0 and 0 = 1 or 0 and 1 = 0 is the "and" operator), || (0 or 0 = 0, 1 or 0 = 1 is the "or" operator), ^(0 = 1, 1 = 0 is the "inversion" operator). Convert numbers or strings into binary calculus and compare bit values. Each comparison returns 0 or 1. The final result is returned by a number or a string translated from a series of resulting bits.
  7. Access to instances of classes, objects, structures: point. Used to access object properties and methods, as well as static class members.
  8. Square brackets []. Used to index arrays and object instances.
  9. Curly braces {}. Separate a block of code in functions, loops, classes and structures, lists.
  10. Parentheses (). Invoking functions and methods, casting types, separating the priorities for performing arithmetic expressions.
  11. Operators of abbreviated conditional construction: ? and:.
  12. Operator to create a new object: new. It is used in constructor functions when creating new objects.
  13. Checking literals for type: typeof sizeof, is, as. The result of the check is a string indicating the type of literal (x = 5, typeof x = int).
  14. Overflow check: checked, unchecked. Return true or false.
  15. Pointer operations: * -> [] &.
  16. Comparison operators: < and >(less and greater), <= and >= (less than or equal, greater than or equal to), !=(unequal).

Example:

Let's look at a few simple examples

Arithmetic
int x = 5;
int y = 10;
intz;

y+x // 15
y*x // 50

Concatenation

string a = "two";
string b = "three";
a+b // twothree

// comparisons
4==5 // false
88==88 // true
90>40 // true
70!=22 // true

Logical

"hello" == "hello" && "hy" == "hy" // both are true, so the result is true
"potatoe" == "orange" || "strawberry" == "strawberry" // one of the comparisons is true, so the result is true

Data assignment

 

Assignment — Pass a literal to a variable. Or saving data to memory. A simple assignment is performed as follows: x = 5. Here, x is an integer variable, the "=" operator assigns a value of 5 to the variable.

In order not to assign the same value to several variables, C# provides a short initialization: int num1, num2, num3. Now initialize them briefly: num1=num2=num3=250.
The assignment operation has the lowest priority.

The expression is executed first, only then the assignment occurs. For example, we need to assign the result of the expression num = 5+5*5. First, the work is performed, then the addition, and at the end the assignment.

Now let's look at examples of abbreviated assignment operations.

Example:

intdigit = 5;

digit +=5; // digit = digit+5 - the result will be 10
digit -=5; // 5
digit *=5 // 25

Conditional expressions

Conditional expressions always return one of two results. This is true or false. Conditional expressions are executed by conditional and Boolean operators. They are used both in simple expressions and logical constructions that allow you to divide the algorithm into its components.

Example:

Comparison operations

operator ==(equals)

varA int = 10;
varB int = 4;
varC bool = varA == varB; false

operator !=(uneven)

int digitA = 20;
int digitB = 14;
bool digitC = digitA != digitB; true
bool digitD = digitA!=20; false

> operator (more)

int с = 10;
int d = 4;
bool e = c > d; // true

< operator (smaller)

int с = 10;
int d = 4;
bool e = c < d; // false




operator >= and <= (greater than or equal to, less than or equal to)

int aa = 100;
int bb = 40;
bool cc = aa <= bb; // false
bool dd = aa <= 25; // true
bool cc = aa >= bb; // true
bool dd = aa <= 100; // true

Logical operators in conditional expressions

Logical operators allow you to map multiple comparisons and, depending on the result, give true or false

Example:

Operator or ||

bool logOR = 55==55 || 34<12; true because the first comparison is true

Operator & &&

bool log& = 32<234 && 100>=100; true because both comparisons are correct — if at least one comparison is not correct, then false

Operator not !

bool not = !» hello»; false, the string is true, and the operator ! checks: is the string not true?

Conditional constructions

Conditional constructions are necessary for choosing the execution of a particular algorithm on one section of the program. If true, then one block of code is executed, if false, then another. There are several types of conditional operators:

  • if(){} — if true, then a block of code is executed, otherwise the algorithm is executed further, and the block is skipped
  • if(){}else{} — if true the if block is executed, if false the else block is executed
  • if(){}else if(){}else — если false в if, тогда проверяется else if, в ином случае выполняется else
  • switch(){case:, case:, case, default} — construct for selecting the correspondence of the literal in parentheses to one of the cases, if it does not match, then the default block is executed

Example:

// if(){}

int numberValue = 10
if(numberValue==10){
Console.write("correct"); // if the expression is true, then this line of code
will be executed // if there is only one line in the block, then curly braces can not be put
}

// if(){}else{}

String name = "Jonathan";

if(name == "Jon"){
Console.write("correct name")
}else{
Console.write("This is a mistake"); // this block will be executed, since the if expression will return false
}

// if(){} else if(){} else{}

intdigit_value = 345;

if(digit_value>1000){
Console.write("if block executed");
} else if(digit_value<1000){
Console.write("The else if block has executed"); // Execute this block
}else{
Console.write(executed else block);
}




// switch case construction

string day = "Friday";

switch(day){
case "Monday": Console.write;
break;
case "Saturday": Console.write;
break;
case "Friday": Console.write; // this line will be executed because the case value and in parentheses are equal
to break; default: Console.write;

}

Pay attention to the "break" statement. It must be put without fail, since in its absence all cases coming after the guess will be executed.

Data Types in C #

Data types are the types of literals that a language supports. Literals are the backbone of programming, since working programs are created due to data processing.

There are 6 total data types in C#:

  1. Integers: int, uint, long, ulong, byte, sbyte, short, ushort - each of them differs only in the size of the allocated memory for the literal.
  2. Floating-point numbers: float, double, decimal.
  3. Character type: char is a letter or number framed in single quotation marks
  4. String: String — plain text framed in double pitches of any Unicode characters, which is an array of characters
  5. Objects: Object - Any of the listed data types for which 4 bytes are allocated in a 32-bit operating system and 8 bytes in 64-bit operating system.
  6. Логические: bool — true или false.

Example:

Integer

int x = 578;
short y = 34;

floating point

double x = 3.45;
decimal y = 34342.33434;

character

char h = 'a';
tank n = 'V';
char r = '3';

Logical

bool s = true;
bool d = false;

line

string m = "Hi, my name is Petya";
string z = "My favorite school subject is geometry";

Objects

object a = 5;
object d = "Hello";
object f = 's';

Output to the console

In order to reflect the text or numbers of the program, they need to be displayed on the screen. One way to output data is to print it to the console. To do this, C# provides a static Console class located in the System namespace, as well as its two static methods: write() - displays everything in parentheses on the console screen; writeLine() — displays all the contents of the brackets and then moves the cursor to a new line.

Example:

Console.write(5);
Console.write(5);
Console.write(5);
// The result will be 555

console.writeline(5);
console.writeline(5);
console.writeline(5);

The result will be
5
5
5

Displaying the Contents of Variables

int num = 78;
Console.write(num); 78

Interpolation is the ability to output several variable values at once with one method along with the text due to the $ symbol and curly braces{}.

Example:

int digit = 458;
char ch = ‘b’;

Console.log($»code of symbol {ch} equals {digit}»); // code of symbol b equals 458

Alternative

Console.log(«code of symbol {0} equals {1}», ch, digit); will be the same as in the previous output

The second variant of interpolation has its own characteristics. For example, this method implies that the first parameter in the Console.WriteLine method represents the output string ("Name: {0} Age: {2} Height: {1}m"). All subsequent parameters represent values that can be embedded in this string (name, height, age). The order of such parameters is important.

For example, in this case, first there is name, then height and then age. Therefore, name will represent a parameter with the number 0 (numbering starts from zero), height is numbered 1, and age is numbered 2. Therefore, in the line "Name: {0} Age: {2} Height: {1}m", the placeholders {0}, {2} {1} the values of the corresponding parameters will be inserted.

Enter data from the console

You can not only output literals to the console, but also enter an arbitrary value inside the console itself. To do this, a static Console.ReadLine() method is provided. When the compiler encounters a call to this method, the user will have to enter a value within the provided data types and press Enter. After that, the execution of the algorithm will continue.

Example:

Console.WriteLine ("Write your last name");

string surname = Console.ReadLine();

Console.WriteLine(surname);

Conclusion: Write your last name
Pupkin + Enter
Pupkin

Explicit and Implicit Type Conversion

Because C# is statically typed at compile time, once a variable is declared, it cannot be declared again or assigned to a value of another type unless that type is implicitly converted to a variable type. For example, you cannot implicitly convert a string to an int. Therefore, after you declare an iobject int, you cannot assign it the string "Hello".

Example:

int some_var;

some_var = «Vova»; Error because a string is assigned to the numeric identifier

However, sometimes you might want to copy the value to a parameter of a variable or method of another type. For example, you might have an integer variable that you want to pass to a method whose parameter type is double. Or, you may need to assign a class variable to a variable of the interface type. These operations are called type conversions.

In C#, you can perform the following kinds of transformations:

  1. Implicit conversions: No special syntax is required because the conversion is always successful and no data is lost. Examples include conversions from smaller integer types to large types and conversions from derived classes to base classes.
  2. Explicit transformations (castings): Explicit transformations require a casting expression . Translation is required when information may be lost during conversion or when the conversion failed for other reasons. Typical examples include converting a numeric character to a type with less precision or a smaller range, and converting an instance of a base class to a derived class.
  3. Custom transformations. Custom transformations are performed by using special methods that you can define to enable explicit and implicit conversions between user-defined types that have no relationship between the base class and the derived class. For more information, see User-Defined Transformation Operators.
  4. Conversions using helper classes: To convert between incompatible types, such as integers and System.DateTime objects, or hexadecimal strings and byte arrays, you can use the System.BitConverter class, the System.Convert class, and the Parse methods built-in -in numeric types such as Int32.Parse. For more information, see How to Convert a Byte Array to int, How to Convert a String to a Number, and How to Convert Between Hexadecimal Strings and Numeric Types.

Implicit conversions (casting)

 

For built-in numeric types, implicit conversion can be performed, where the stored value can fit into a variable without truncation or rounding. For integer types, this means that the range of the source type is the correct subset of the range for the target type.

For example, a variable of type long (a 64-bit integer) can store any value that can store an int (a 32-bit integer). In the following example, the compiler implicitly converts the num value on the right to the long type before assigning it to BigDigit.

Example:

int digit = 3434234234;
long BigDigit = digit; assignment is successful and int is converted to long because the long type is greater than int

Explicit type conversions

However, if the conversion cannot be performed without the risk of information loss, the compiler requires that you perform an explicit transformation called a conversion of . Casting is a way to explicitly tell the compiler that you are going to perform a conversion and that you know that data loss may occur or casting may fail at run time.

To cast, specify the type to which you are converting, in parentheses before the value or variable that you want to convert. The following program converts double to int. The program will not compile without a ghost.

double some_num = 1454.7;
int val;

Convert an integer to a floating-point
type val = (int)some_num; the type in parentheses indicates an explicit conversion of
Console.WriteLine(a); 1454

Data Types: Values and References

Significant types are primitive data types such as numeric, string, characters, logical. Reference types are objects. Meaningful types are stored on the stack. References in a heap.
An object identifier is a reference to an object on the heap. The difference between a reference type is that multiple identifiers can refer to a single object. Modifying an object through a single identifier will change it for all identifiers.

Example:

Significant type

int b = 5;
int c = b; // 5

c = 10;
Console.write(b); // 5

As you can see from the example above, we kept the first variable in the second. By changing the second variable, the value of the first remains the same. Now let's look at the same operation with the reference type.

class House(){
public int width: 120;

}

House motel = new House();

House shop = motel;

Console.write(motel.width); // 120
Console.write(shop.width); // 120

change the property of one of the objects

motel.width = 140;

Console.write(motel.width); // 140
Console.write(shop.width); // 140

This is because when you assigned a motel object to a shop object, you simply passed the same object to two references. They both refer to the same object. If we created a shop through the new operator, then it would already be two different objects.

Cycles

As with any other language, C# supports four types of loops: for, for each, while, do while. Loops are a way to shorten code when you need to do the same operation many times.

Цикл for

Example:

for(int x = 0; x>=10; x++){
Console.Write("a");
}

output: a a a a a a

Here, the declared variable x = 0 is the starting position of the counter, x>= 10 is the final position. The x++ increment increments the counter by 1 each iteration of the loop. An iteration is a single execution of a loop. We had 10 iterations.

The break and continue statements define how the loop will execute. Break stops the loop completely, and then continues to execute the algorithm outside the loop block. The continue statement skips a single iteration.

Example:

// continue

for(int x = 0; x>=10; x++){
if(x==10) continue; // skip last iteration
Console.Write("a");
}

Result: a a a a a a a a = 9 times

// break

for(int x = 0; x>=10; x++){
if(x>5) break; // exit from the loop
Console.Write("a");
}

Outcome: a a

While and do while loop

 

This works with both the counter and Boolean expressions. The increase in the counter should be indicated not in parentheses, but in the block int s = 0;

while(s!=10){
Console.Write(«b «);
s++;

}

Outcome: b b b b b b

Here, the variable s is 0. Each iteration increments the counter by 1 at the expense of s++, and true in parentheses. When s is 10, it is false in parentheses. The loop stops working. You can also use the break and continue statements here.

The do while loop has a similar syntax, its only difference is that the first iteration is performed without fail if it does not have continue. The remaining iterations are executed as expected until the condition in parentheses is met.

Example:

do{
//first time executed, other iterations depending on the condition
}while(true)

Foreach Loop

This loop is used to iterate through the arrays, which will be discussed in more detail later. Of course, the array can be iterated through the previously considered loops. But foreach is better adapted specifically for arrays and allows you to save memory (very little) on its creation.

Example:

char[] symbols = {'a', 'b', 'c', 'd'}; // created an array of characters

now convert all characters to uppercase using a loop

foreach(int x in symbols){
symbols[x] = symbols[x]. ToUpper();
}

Console Write(symbols); // A B C D

Arrays

Arrays are a collection of values of the same type that have an ordinal index and a single identifier. An example is the list of students: Class B Magazine (identifier), Pupkin, Pushkin, Zhorikov, Samsonova. In programming, the array looks like this: char[] arr = {'v', 'a' ,'d', 'r'}; Here we created an array of four elements. Each element has its own ordinal index. The symbol v has a zero index, the rest are in the order of the queue. The elements of the array start at zero.

What is in our array:

  • char[] is the type declaration of the elements in the array, and the square brackets indicate that the array is being created.
  • arr is the identifier of the array;
  • {v', 'a' ,'d', 'r'} is an array of four elements with indexes [0], [1], [2], [3].

Why do we need arrays when each value can be packaged into a separate variable? The answer is simple – for convenience. It is impractical to store logically related literals in different variables. It is much more convenient to use arrays for this, as was shown in our student journal. There are several ways to create arrays. Let's look at them with examples.

Example:

create the same array in different ways

int[] numbers = {34, 43, 72, 90};

int[] numbers = new [] {34, 43, 72, 90};

int[] numbers = new int[] {34, 43, 72, 90};

int[] numbers = new int[4] { 1, 2, 3, 5 }; with an indication of its length

manual initialization

int[] numbers = new int[];
numbers[0] = 34;
numbers[1] = 43;
numbers[2] = 72;
numbers[3] = 90;

If the array is created with a length, but no assigned elements, that is, an empty array, then in this case the empty elements will receive a default value. For numbers and characters, this value is 0, for strings it is empty strings ".".

Our array is currently limited to four elements, so we can't go to the fifth. Even if the array is empty, the existing elements are populated with default literals. But if you refer to an element that is outside the array with an index of 5 as in our case, the compiler will give an error.

Let's consider the example of the output of all the values of the array. Example:

int[] massiv = new int[5]; created a new Array
Console.WriteLine ("Array Length {0}", massiv. Length); display the length of the array, the Length property allows you to know the length of the array

fill the array through a for loop

for(int x = 0; x<=massive. Length; x++){
massive[x] = x+5;

}

output the contents of the array

foreach(num in massive){
Console.WriteLine(massive[num]);

}

Output:
Array length 5

6, 7, 8, 9, 10

Let's try to go beyond the array.

Console.WriteLine(massiv[6]); IndexOutOfRangeException — Error: Accessing an index outside the array

An array declared with a fixed length may not be fully populated. Then the rest of the empty elements will receive the default literals.

Multidimensional array

A multidimensional array is an array of arrays. That is, the elements of the array are other arrays. A two-dimensional array is an array of arrays. A three-dimensional array is an array of arrays whose elements are also arrays. Let's look at the example of creating a two-dimensional array.

Example:

int[][] two_dimension_array = {{23, 34, 56}, {54, 89, 10}}; declaring a two-dimensional array is done through double brackets

Console.WriteLine(two_dimension_array[0][0]); // 23
Console.WriteLine(two_dimension_array[1][0]); // 54
Console.WriteLine(two_dimension_array[1][2]); // ten

you can also declare a two-dimensional array with a fixed length

int[][] two_dimension_array = new int[2][4]; an array of two arrays is declared, each containing 4 elements

Console.WriteLine(two_dimension_array.Length); // 2
Console.WriteLine(two_dimension_array[0]. Length); // four

fill the array through a loop

for(int i = 0; i<=two_dimension_array. Length; i++){ // the number of iterations is equal to the number of arrays in the array
for(int j = 0; j<=two_dimension_array[i]. Length; j++){ // the number of arrays is equal to the number of elements in iterations
two_dimension_array[i][j] = j;
}
}

It is logical to assume that arrays can be very different in the number of dimensions. However, in practice, two-dimensional arrays are most often used, since it becomes difficult to work with a large number of measurements.

Methods (functions)

 

Functions are of great importance in programming. You can endlessly discuss what benefits they bring. However, their main meaning is to save the programmer's time, simplify the algorithm and save memory. In object-oriented languages, functions are methods. Any, even single-line program in C# is an instance of a class. The main function of Main is also a method.

Functions are part of procedural programming languages and others other than OOP. In object-oriented functions, methods are used. Methods in C# are parts of a larger program that perform specific tasks. You can use them to clean up your code by splitting it into separate parts. They can also be used in more than one place, allowing you to reuse the previous code.

In C#, as in other C-like languages, methods can reside in the host program or can reside in libraries, which are external files that contain classes and subroutines that you can import into your program. This makes it easy to distribute them and use them in multiple programs.

The method is described once. Its description can take from one to several lines. The method block contains lines of code that will be executed each time the method is called. The point of this system is that the method is called in just one line. If it were not for the methods, the programmer would have to manually enter the statements of the method code block if necessary.

In programming, calling a method starts the process of executing a block of statements. This process is performed when the programmer wants to execute a method, so it must be called using this functionality. As soon as the method name calls the method, it moves on to the description of the method, where all the operators inside it are executed. The return statement is then executed and the final value is returned to the calling method.

Let's look at a conditional example that has nothing to do with C# syntax. Example:

the function of boiling the kettle {
pour water into the kettle;
turn on the kettle;
wait for the automation to work;

}

Imagine that we need to boil the kettle 25 times in the code. As you can see in the method block, we have 3 lines of code. And that: 25 * 3 = 75. You will have to write 75 lines of code to boil the kettle 25 times. Just imagine how this will affect the programmer himself, how much text memory will take. It's called ridiculously disposing of memory.

The function call, as mentioned earlier, is made in just one line. Our function will be called as follows: boil the kettle(). This command executes the lines of code that are enclosed in the block. So we only need to call this function 25 times. If you want to call it 25 times in a row, and not in different parts of the code, then it is better to do it through a loop as follows. Let's also analyze this with a conditional example.

Example:

for(int h = 0; h<=25; h++){
boil kettle();
}

As you can see, this method allowed us to get by with only three lines of code, which significantly saves on the size of the executable file. The programmer does not need to pile up the code with the same type of calls.
Packing a set of statements into a single module helps reduce the number of repetitions of the same code over and over again, or to use a particular operation over and over again.

Writing multiple statements under a common name (method name) and calling that name multiple times can save programming effort: writing the same code makes it possible to reuse the same code to save excessive memory usage. In this chapter, you will learn about the use of methods in C#, their syntax, and various characteristics.

Method Definition

 

With the basic concepts of methods, we have dealt with in more than detail. Now it's time to understand how methods are defined by C# rules. There are two kinds of methods: those that simply process the data and those that process the data and return the result. The method definition operator that returns nothing looks like this: public static void method_name(){}. It consists of the following elements:

  1. Public static- access modifier. In OOP, all class members have their own access modifier. In the main class outside of the Main function, all methods must be static. In total, there are several access modifiers. These are public, static, private, protected. In our case, the method is public and static at the same time.
  2. Void is a keyword that indicates that the method returns nothing. A similar one is present in the Main method.
  3. method_name is the id of the method, that is, its name.
  4. () — parentheses indicate that this is a method, and also take parameters. Our method is without paramers.
  5. {} is a block of code that is executed when the method is called.

Example:

public static void sayHelloThreeTimes(){ // define and declare the method once
Console.Write("Hello");
Console.Write("Hello");
Console.Write("Hello");
}

call the method

sayHelloThreeTimes();
sayHelloThreeTimes();
sayHelloThreeTimes();

Console output:
hello hello hello
hello hello hello
hello hello

Now it's time to look at the methods that return values, their signature is different in that instead of the word void, you put the type that the method will return, and in the body of the function put the keyword return and after it what should be returned.

Example:

public static int Multy_two_digits()
{
int x = 5;
int y = 5;
return x * y;

}

int result = Multy_two_digits();
Console.Write(result); // 25

In the method block, we defined only three lines of code. The return statement returns the result of an arithmetic expression.

Methods with parameters

 

Parameters allow you to enter arbitrary values to use each time a method is called. A parameter list is a valid identifier, separated by a comma-delimiter, used to enter parameters of different types, and the data type precedes each. They are enclosed in parentheses. It is also possible that a method cannot have a parameter in the parameter list. Let's look at the example of defining a method with parameters.

Example:

public static int Multy_two_variable(int a, int b)
{

return a * b;

}

Console.WriteLine(Multy_two_variable(2,2)); // 4
Console.WriteLine(Multy_two_variable(25,2)); // 50

As you can see, the method is similar to the previous one. Parameters are specified with a specific type and can have any identifier. If you specify the identifiers of global variables as parameters, this will have nothing to do with global variables. Simply, their values will be passed to the parameters.

Two parameters, the integer a and the integer b, have been passed to this method, so you provide input for the subroutine (method). The return statement stops the routine and, depending on the type of output, can output a value of the same type as the output type.

The return statement can be used not only to return a value. It is used simply to exit the function. Let's analyze this more clearly by slightly changing the previous method.

public static int Multy_two_variable(int a, int b)
{
if(a==0 && b==0) return; // early exit from the function if the parameters are not defined
else return a*b; // if the parameters are greater than 0, then the multiplication is performed and the result is returned

}

int a = Multy_two_variable(0, 0);
int b = Multy_two_variable(3, 3);

Console.WriteLine(a); Error - The variable contains no result. We haven't returned anything here to
Console.WriteLine(b); 9

More compact method definition

C# provides so-called lambda expressions, which allow you to slightly reduce the definition of methods. Let's imagine that we have an arbitrary method.

Example:

static void SaySomething() // simple method written normally defined
{
Console.WriteLine("My name is Petra");
}

Now let's shorten it with lambda expressions.

Example:

static string SaySomething() => Console.WriteLine(«My name is Petya»);

If we used the return operator instead of displaying, the lambda expressions would look like this:

static string SaySomething() =>»My name is Petra»;

Array as parameters

Parameters can be more than just simple local variables. You can also pass an array as a parameter. To do this, use the params keyword. In this case, we are not talking about the transfer of a simple array. It's about passing an indefinite number of parameters.

Example:

static void arr_params(params int[] integ)
{
int result = 0;
for (int i = 0; i < integ. Length; i++)
{
result += integ[i];
}
Console.WriteLine(result);

}

Addition(1, 2, 3, 4, 5); call a method with an arbitrary number of parameters

int[] array = new int[] { 1, 2, 3, 4 };
Addition(array); the number of parameters is equal to the number of elements in the array, and the values are set to the values of the array

Addition(); a call without parameters will also not result in an error

The params array should represent the type of parameters we are going to use. In the previous example, we had integer parameters. If we are going to use other single parameters in addition to the array, they are specified before the params keyword.

Example:

static void Many_Params( int a, string s, params int[] integ){} // single parameters are specified before the params array

static void Many_Params(params int[] integ, int a, string s){} // such a definition will not work, since the array is specified before single parameters

There are situations when, instead of an array of parameters, you specify just an array as a parameter: static void Many_Params ( int a, string s, int[] integ). In this case, you cannot vary the number of parameters when the function is called. An array must be passed as a parameter, not otherwise.

Local variables in methods

Local variables are declared inside methods and exist only when that method is called. Once the method is returned, the memory allocated to any local variables is released.

Example:

int x = 5;
int z = 10; // global variables of the main function

static void change_variables(int a, int b){
a = a+5;
b=b+5;
Console.WriteLine(a);
Console.WriteLine(b);
}

change_variables(a, b); // 10 15

Console.WriteLine(a); 5 - Global variables have not changed because only their values have been passed as a parameter.
Console.WriteLine(b); ten

The parameters themselves become local variables and cannot change global variables. The boundaries of various contexts can be associated with opening and closing curly braces, as in this case, which set the limits of a code block, a method, a class. When working with variables, keep in mind that local variables defined in a method or code block hide class-level variables if their names match.

Pass parameters via link

The ref keyword in C# is used to pass or return references to values in or out of methods. Essentially, this means that any change to a value passed through a link will reflect that change because you are changing the value at the address, not just the value. This can be implemented in the following cases:

  1. To pass an argument to a method by reference.
  2. To determine the method signature to return a reference to the variable.
  3. To declare the structure as ref struct.
  4. As a local link.

Example:

public static void addValue(int a){
a += 10;
}

Define subtractValue
// pass parameters through the ref link

public static void subtractValue(ref int b){
b -= 5;
}

Writing the basic algorithm

// Initialize variables
int a = 10, b = 12;

// Display set values
Console.WriteLine("Initial value of a is {0}", a);
Console.WriteLine("Initial value of b is {0}", b);
Console.WriteLine();

Call the method by the value of
addValue(a);

Console.WriteLine("Value of a after addition"+
"operation is {0}", a);

Call the method by reference
subtractValue(refb);

// Display the value of b without reference but by value
Console.WriteLine("Value of b after "+
"subtration operation is {0}", b);

The conclusion would be the following text:

Initial value a equals 10
Initial value b equals 12

Addition value 10
The value of b after the subtraction operation is 7

What happened here? Here we define two methods, addValue and subtractValue. The addValue method is a method that changes only the value of its parameter. Therefore, when the value of 'a' is displayed after passing it as a parameter to addValue, its value does not differ.

While the subtractValue method uses a parameter reference, the ref keyword specifies the same thing. Subsequently, when the 'b' value is displayed after passing it as a parameter for subtractValue, you can see that the changes are reflected in its value. The ref keyword must be used in the definition of the method as well as when it is called.

You can also use the ref keyword with an instance of the class. In the program below, we have a Complex class for representing complex numbers. The class also consists of an update method that uses a reference to an object and reflects the updates made to the value of the real and imaginary parts of the object.

Keyword out

It is similar in functionality to the ref keyword. However, unlike ref, out does not require the variable to be initialized before passing it as a parameter.

Example:

static int Add_numbers(out int a)
{
a = 0;//assigned initial value
a++; //incremented by 1
return a;
}

write down the main algorithm in the main
int b function;
Console.WriteLine($"Method Output: {Addition(out b)}. The value of the variable after the method is executed: {b}");

The output will be method output:1. The value of the variable after the method is executed: 1.

Motorcades in C #

Tuples are a convenient way to store different values. Tuples are somewhat similar to arrays, only they can store different values.

Example:

Ways to advertise tuples

var tupleOne = new Tuple(1);

var tupleTwo = new Tuple(1, «test»);

var sevenelementTuple = new Tuple(1,2,3,4,5,6,7);

As you can see from the code above, three types of tuples have been created. Each has read-only properties with the names Item1, Item2, Item3, and so on. We can access the elements of the tuples through the properties. tupleOne.Item1 will return 1, this tuple has no other values, so accessing the Item2 property will result in an error.

TupleTwo is created with two types of type parameters, i.e. int and string. In this way, we can create a tuple containing up to seven parameters. That is, tuples store elements of any parameters, this is what distinguishes it from an array.

Total

 

The syntax of C# incorporates all the best of the languages C, C++, Java. It has a more structured program unlike other languages. A huge number of libraries and classes have been written for it. It is designed to develop Windows and web applications. It is part of the Unity engine and is used for game development.

This article listed the basic rules for writing programs in C#. However, this is not a complete programming guide. Since we have not analyzed in this article such a concept as "Object-oriented programming".

According to this programming paradigm, a huge number of books have been created. By simplifying software development, this paradigm is not easy to learn. Those who have studied functional or procedural programming may find it difficult to migrate to OOP.

Of course, you can also program in C# in a procedural style. However, then this will not make it an effective language. When learning only the syntax of the language, do not forget about practice and experimentation with various classes and graphic libraries.

Still, C# was created to create powerful applications for the Windows operating system. It allows you to create high-load applications for the Web using ASP.NEt, as well as work with relational databases.