2. C# Language Basics || C# 10 Flashcards

1
Q

What is a statement block?

A

Series of statement surrounded by a pair of braces (all of this is a method)

int feetToInches (int feet)
{
  return 12 * feet;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is an “assembly”?

A

Assemblies are the fundamental units of deployment, version control, reuse, activation scoping, and security permissions for .NET-based applications. An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. Assemblies take the form of executable (.exe) or dynamic link library (.dll) files, and are the building blocks of .NET applications. They provide the common language runtime with the information it needs to be aware of type implementations.

In .NET and .NET Framework, you can build an assembly from one or more source code files. In .NET Framework, assemblies can contain one or more modules. This way, larger projects can be planned so that several developers can work on separate source code files or modules, which are combined to create a single assembly.

Assemblies have the following properties:

Assemblies are implemented as .exe or .dll files.

For libraries that target .NET Framework, you can share assemblies between applications by putting them in the global assembly cache (GAC). You must strong-name assemblies before you can include them in the GAC.

Assemblies are only loaded into memory if they're required. If they aren't used, they aren't loaded. Therefore, assemblies can be an efficient way to manage resources in larger projects.

You can programmatically obtain information about an assembly by using reflection.

You can load an assembly just to inspect it by using the MetadataLoadContext class on .NET and .NET Framework. MetadataLoadContext replaces the Assembly.ReflectionOnlyLoad methods.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Name some predefined and custom types. What is the main difference between them?

A

Predefined: string, int, bool;
Custom: Person, Salary, Payment;

Predefined types dont need to be instantiated like custom does:

int three = 3;
Person jack = new Person(“Jack”);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How would you describe static class?

A

Static members (data and function members) dont operate on the instance of the type e.g. Console.WriteLine() and not var x = new Console. Methods of the static class are available through class name (Console) and not instance name (x).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is a implicit conversion?

A

short -> int -> long;
Implicit conversion happens automatically: int -> long
Allowed when both are true:
1. The compiler can garuantee that they will always succeed;
2. No information is lost in conversion;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is an explicit conversion?

A

Explicit conversion require a cast and this type of conversion is required when one of the following is true:
1. The compiler cannot garuantee that they will always succeed
2. Information might be lost during conversion

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What are the types categories in C#?

A

• Value types
• Reference types
• Generic type parameters
• Pointer types

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Which types lay under the value type? (Name more than 3)

A

Value types comprise most built-in types (all numeric types, char and bool types) as well as custom struct and enum types

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Which types lay under reference type?

A

All classes, array, delegate, interface types. Includes predefined string type as well

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is the fundamental difference between value and reference types?

A

The way they are handled in memory. Value type objects are always copied or created, but assigning a reference type the reference is copied not the object instance.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What are nullable variables?

A

Variables which references points to no objects. Thats why we get NullReferenceException. This also means that value type cannot have a null as value if not declared otherwise (?)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is the difference between i++ and ++i?

A

Both are adding 1 to the variable, but the difference is whether we want variable’s value before or after the increment:

console.writeline(x++); outputs 0; value is now 1;

console.writeline(++x); outputs 1; value is 1;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is “short-circuiting”? Where it is encountered?

A

It is encountered when using && and || operators in a condition (comparing to & and |). In short if the first part of the condition is not true the following part is not evaluated, therefore if the first statement is false this statement wont throw a NullReferenceException
If ( sb != null && sb.Length >0)…

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is a ternary operator?

A

Ternary operator ( condotional operator or shorthand if statement) - has the form “question ? AnswerA : AnswerB”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Give an example of verbatim string

A

var string = @“\\server\files\heloworld.cs”;
It can also support multiple line strings

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Give an example of interpolated string

A

var sentence = $”Hi, my name is {name}!”;

17
Q

Can we combine verbatim and interpolated strings? How?

A

Yes we can. Interpolated string symbol must go before verbatim like so:
var string = $@“mixed string {x}”;

18
Q

What is an array?

A

Array represents a fixed number of variables (elements) of a particular type. The elements in array are always stored in a contiguous block of memory providing highly efficient access

19
Q

What’s an array initialisation expression?

A

Expression which lets you declare and populate an array in a single step:
char[] vowels = {‘a’, ‘e’, ‘i‘, ‘o ‘, ‘u’};

20
Q

What are the other types of array?

A

Multidimensional arrays: rectangular and jagged arrays.
Rectangular: represent n-dimentional block of memory.
Jagged arrays: arrays of arrays

21
Q

What is a variable?

A

A variable represents a storage location that has a modifiable value. A variable can be:
a local variable,
parameter (value, ref, out, or in),
field (instance or static) or
array element

22
Q

What are the stack and the heap? What are the differences between them?

A

Stack: block of memory for storing local variables and parameters. The stack logically grows and shrinks as a method or function is entered and exited. If the value type is not a local variable or parameter it lives wherever the variable was created.
Heap: memory in which objects (reference-type instances) reside. Whenever new object is created it is allocated on the heap and the reference to that object is returned. During a programs execution the heap begins filling up as new objects are created. The runtime has a garbage collector that periodically deallocated objects from the heap so the program does not run out of memory. An object is eligible for deallocation as soon as it’s not referenced by anything that’s itself “alive”

23
Q

What is a definite assignment?

A

Definite assignment is a concept in C# that ensures that all local variables are initialized with a value before they are used in the program.

When you declare a variable in C#, the compiler will ensure that you assign a value to it before you try to use it. If you attempt to use an uninitialized variable, you will get a compile-time error

  • local variables must be assigned a value before they can be read;
  • function arguments must be supplied when a method is called
  • all other variables are automatically initialised by the runtime
24
Q

What are the default values for most common types? How to get them?

A
  1. Reference type: null
  2. Numerics and enum types: 0
  3. Char type: ‘\0’
  4. Bool type: false

To get them we can use “default” as:
Default(decimal) or decimal smth = default;

25
Q

Explain parameter modifier ref. how does it work under the hood?

A

“To pass by reference”. When creating and passing a variable with a ref modifier it refers to the same memory location. So when a parameter is passed to the method where it is changed, the original value in a variable also changes:

Int x = 8;
Foo (ref x);
Console. WriteLine(x); // x is now 9;

Static void Foo (ref int p){
p++;
}
26
Q

How does the “out” modifier work? Where is it used most frequently?

A

Parameters with out modifiers does NOT need to be assigned before entering the method and it MUST be assigned before coming out of it

string a, b;
split(“Inga Reikale”, out a, out b);
Console. Writeline(a); // Inga
Console.Writeline(b); // Reikale

static void Split(string fullName, out string firstName, out string lastName){
int i = fullName.LastIndexOf(“ “);
firstName = fullName.Substring(0, i);
lastName = fullName.Substring(i+1)
}
27
Q

What is a “params” modifier?

A

Params modifier if applied to the last parameter of a method. It allows the method to accept any number of arguments of a particular type:

int Length(params int[] ints){
Console.WriteLine(ints.Length);
}

int totalLength = Length(1, 4, 5, 7);
28
Q

What are the optional parameters? How do you write one and what are the requirements?

A

A parameter is optional if it specifies a default value in its declaration:
void Foo(int x = 2){ Console.WriteLine(x);}
When calling Foo() we will get 2 printed in console even if we didn’t supply any parameters
Requirements:
- optional parameters cannot be marked with ref or out
- mandatory parameters must occur before optional parameters in both declaration and the method call

29
Q

How operators are classified in C#?

A

Operators can be classed as unary, binary or ternary depending on the number of operands they work on (one, two or three). The binary operator ls always use infix notation in which the operator is placed between the two operands

30
Q

How does the null-Coalescing operator, null-conditional and null-Coalescing Assignment operator look like?

A

null-Coalescing : var x = y ?? z; // if y is not null take y, else take z;
null-Coalescing Assignment: x ??= y; // if x is null assign y to x, else leave x as it is
null-conditional: var x = y?.ToString(); // if y is not null assign the returned item from he method, else assign null to x;

31
Q

How can you use switch statement to check a type?

A

With an ‘object’ type for the switch statement:

void TellTheType(object x)
        {
            switch (x)
            {
	
                `case int i:`
							// if not interested in value, we can use '_' instead of 'i' here;
                    Console.WriteLine($"Its an int: {i}");
                    break;
                case string s:
                    Console.WriteLine($"This is a string: {s}");
                    break;
                default:
                    break;
            }
        }
32
Q

How can you write a switch statement as an expression?

A
var x = y switch
{
  1 => "one",
  2 => "two"
  _ => "default value"
};
33
Q

Name all iteration statements

A
  1. While
  2. Do-While // event will happen at least once
  3. For
  4. Foreach
34
Q

Name all Jump statements

A
  1. Break
  2. Continue
  3. Goto
  4. Return
  5. Throw
35
Q

What is a ‘using’ statement?

A

The ‘using’ element provides an elegant syntax for calling ‘Dispose” on objects that implement IDisposable within try/finally block.

using (FileStream... )
{
  // write to file
}

after all the necessary actions are finished the Dispose method is called on the method/block that implements the IDisposable interface

36
Q

What is a namespace?

A

The namespace keyword is used to declare a scope that contains a set of related objects. You can use a namespace to organize code elements and to create globally unique types.
pvz System.Collections.Generic

37
Q

Let’s say that we have 2 identical namespaces in two different assemblies (.dll files) and you want to reference them but the program can’t compile because the name is ambiguous. How you should solve this?

A

By using the extern aliases.
First need to modify application’s .csproj file, below the reference to our assemblies need to add:
<Aliases>Thing1</Aliases>
Then in desired file use this extern directive:

extern alias Thing1;
Thing1.NamespaceObject.ClassObj x = new();