6. .NET Fundamentals || C#10 Flashcards

1
Q

What is the difference between char.ToUpper() and char.ToUpperInvariant() ?

A

When dealing with different culture charaters sometimes it can reference a different character. e.g. to upper of ‘i’ in Turkey is “I’ with a dot on top, which is totally different char than simple “I” in English. To avoid that we can call methods that end in “Invariant” such as ToUpperInvariant which will always return the English cultures result (in this case a simple “I”)

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

Is string a mutable or immutable type?

A

String is a immutable (unchangable) sequance of characters

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

Can string be null?

A

Since string a reference type, it can be null:
string s = null; // OK

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

Can we use ‘foreach’ to iterate through strings character? Why?

A

Yes, we can. This is because string implements IEnumerable<char> :
foreach (char c in "123") Console.WriteLine(c + ","); // 1,2,3,</char>

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

What happens when you edit a string under the hood?

A

Since string is an immutable type, each time you “manipulate” it a string returns a new one, leaving the original untouched (the same goes when you reassign a string variable)

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

What does string.Substring(a, b) and string.Substring(a) do?

A

Extracts a portion of string:
~~~
string s = “abcdef”;
s.Substring(0, 3) = “abc”
~~~
OR gets the remainder if we put only one parameter:
s.Substring(2) = "cdef";

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

What does string.Insert() and string.Remove() do?

A

Inserts and Removes characters at specified position:
string s = “abcdef”;
s.Insert(3, “, “) = “abc, def” // inserts before the 3rd char
Remove(where, howMuch):
s.Remove(0, 2) = “cdef”

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

What does string.PadLeft() and string.PadRight() do?

A

Pad a string to a given length with a specified character (if the second paramenter is not given - the space is inserted):
string s = “abcdef”; // Length == 6
s.PadLeft(8, ‘-‘) = “–abcdef” // Length == 8
If the given string is longer than what is specified in PadLeft/PadRight the string is returned unchanged

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

What does (string) TrimStart, TrimEnd and Trim do?

A

TrimStart and TrimEnd remove specified characters from the beginning or end of a string; Trim does both. By default these functions remove whitespace characters (including spaces, tabs, new lines and Unicode variations of these):
“ abc \t\r\n “.Trim() // “abc”

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

What does (string) Replace() do?

A

Replaces all (nonoverlapping) occurrences of a particular character or substring:
“to be done”.Replace(“ “, “-“) // “to-be-done”

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

What does (string) ToUpper or ToLower do?

A

Returns uppercase or lowercase variant of the string while respecting the current language settings. To always apply English language settings ToUpperInvarriant or ToLowerInvariant should be used

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

How does string.Split() works?

A

Split divides string into pieces. By default it uses white space characters as delimiters;
Split also accepts StringSplitOptions enum which has an option to remove empty entries;
this is useful when words are separated by several delimiters in a row
string[] words = “The quick brown fox”.Split();
foreach (string w in words)
Console.WriteLine(w + “|”); // The|quick|brown|fox

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

How string.Join() and string.Concat() work?

A

The Join method works opposite of Split() - it requires a delimiter and a string array;
string[] words = “The”, “quick”, “brown”, “fox”;
string w = string.Join(“ “, words);
Concat method is exactly equivalent to the + operator and accepts only a params string array and applies no separator (to be exact the compiler translates + to Concat):
string.Concat(“The”, “quick”, “brown”, “fox”) ==
“The” + “quick” + “brown” + “fox”;

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

What is a composite format string?

A

The master string that includes the embedded variables. It is called using string.Format method
string masterString= “It’s {0} degrees in {1} on this {2} morning”;
string s = string.Format(masterString, 5, Utena, DateTime.Now.DayOfWeek);
// “It’s 5 degrees in Utena on this Saturday morning”
Each number in curly brackets is called a format item. The number corresponds to the arguments position. There could be second parameter which can be:
1. A comma and a minimum width to apply
2. A colon and a format string
The minimul width is useful when aligning columns - if the value is negative the data is left-aligned , otherwise - right-aligned
string s = “Name={0, -20}, Credit Limit={1, 15:C}”
CW(string.Format(s, “Inga”, 2000)); // “Name=Inga Credit Limit = $2, 000.00”

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

What are the two basic algorithms for string comparisons? Define them

A

Ordinal and culture sensitive algorithms
- Ordinal comparisons interpret characters simply as numbers (according to their Unicode value); == operator and Equals() always performs ordinal case-sensitive comparison; comparison scheme : (aAbBcC…)
- Culture sensitive comparisons interpret characters with reference to a particular alphabet. There are two special cultures: the “current culture” which is based on a settings picked up from computers control panel and the “invariant culture” which is the same on every computer (closely matches American culture) comparison scheme : (ABCDabcd)

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

Are the string.Equal() and string.CompareTo() methods the same?

A

No.
Equals() metod performs ordinal oder comparison to string. Returns true/false.
CompareTo() method performs culture-sensitive, case-sensitive order comparison. Implements IComparable interface, a standart comparison protocol used across .NET libraries.
Therefore if we apply this method on “ū” and “u” the strings wouldn’t be equal. Returns -1, 0 or 1 depending if the value comes after, before or alongside the second value

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

What is StringBuilder?

A

The StringBuilder class (System.Text namespace) represents a mutable (editable) string. With a StringBuilder you can Append, Insert, Remove and Replace substrings without replacing the whole StringBuilder

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

Which is better to call string.Concat() or StringBuilder.Append()

A

StringBuilder.Append() is much more efficient than repeatedly concatenating ordinary string types.
Each time we modify a regular string, a new string is created since string is immutable. But when we are using stringBuilder (mutable type) we can add new values at the end or at specific point without creating new StringBuilder object.

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

Let’s say we have a StringBuilder which has around 2million characters inside (that accumulates around 2MB of memory). We set it’s Length to 0, what’s its allocated memory right now?

A

The same 2MB. Since setting Length to 0 does not release the memory. If we want to do that we need to create a new string builder and allow the old one to drop out of scope (and be garbage collected)

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

What is a text encoding?

A

A text encoding maps characters from their numeric code point to a binary representation. In .NET text encodings come into play primarily when dealing with text files or streams. When you read a text file into a string a text encoder translates the file data from binary into the internal Unicode representation that the char and string types expect.
There are two types of text encodings in .NET:
1. Those that map Unicode characters to another character set
2. Those that use standart Unicode encoding schemas (UTF-8, UTF-16 and UTF-32 (and obsolete UTF-7)) Each differs in space efficiency. UTF-8 is the most efficient - it uses between one and four bytes to represent each character; First 128 character require only one byte, which makes it compatible with ASCII

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

What is a high-surrogate and a low-surrogate?

A

A high surrogate and a low surrogate are two 16-bit characters that are used together to represent a single character in the Unicode range U+010000 to U+10FFFF.

The high surrogate represents the first half of the character code, and the low surrogate represents the second half. These characters are also known as lead and trail surrogates, respectively.

In C#, high surrogates have a value in the range U+D800 to U+DBFF, and low surrogates have a value in the range U+DC00 to U+DFFF. When combined, the high and low surrogates form a single character that can be used to represent characters outside the BMP range.

For example, the Unicode character ‘🙂’ (SMILING FACE WITH SMILING EYES) can be represented as a surrogate pair in C#:

char highSurrogate = ‘\uD83D’;
char lowSurrogate = ‘\uDE42’;
string smiley = new string(new char[] { highSurrogate, lowSurrogate });

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

Which structs are used to represent dates and times?

A

DateTime, DateTimeOffset, TimeSpan, DateOnly and TimeOnly. All of them are immutable

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

What are the differences between DateTime and DateTimeOffset?

A

DateTime and DateTimeOffset are both used to represent date and time information in C#, but they have different semantics.

DateTime represents a date and time value, but it does not include any information about the time zone or offset. This means that a DateTime value is ambiguous, as it can be interpreted as any time in any time zone.
DateTimeOffset, on the other hand, represents a date and time value that includes information about the time zone offset from UTC (Coordinated Universal Time). This means that a DateTimeOffset value is unambiguous, as it specifies the exact date and time in a specific time zone

24
Q

What is a DateTimeKind?

A

The DateTimeKind enumeration in C# is used to specify the type of a DateTime value. The possible values of DateTimeKind are:

Unspecified: The DateTime value does not have a specified kind and can be interpreted as either a local time or a Coordinated Universal Time (UTC) value.

Local: The DateTime value is a local time.

Utc: The DateTime value is a UTC time.

You can use the DateTimeKind enumeration by setting the Kind property of a DateTime object:

DateTime now = DateTime.Now;
now = new DateTime(now.Ticks, DateTimeKind.Local);

25
Q

How the DateTime objects are compared if we have two objects with same date but one DateTime with DateTimeKind ‘unspecified’ and the other with ‘Local’?

A

When comparing two DateTime objects only their “ticks” are evaluated, so if the date and time is the same but the DateTimeKind is the only difference, the DateTime objects are considered equal

26
Q

Define Parse() and TryParse() methods

A

All simple value types (bool, int, char, Guid…) have these two methods.
Parse() converts from string type to the type which is calling this method:
int.Parse(“123”) // int type is calling
char.Parse(“-“) // char type is calling
In case of invalid conversion an FormatException is thrown. To avoid them we can use TryParse() method, which return type is bool indicating if the conversion was successful or not. The converted output is set via ‘out’ modifier

27
Q

How can we format a number e.g. 300 to be shown as the LT currency without hard-coding it?

A

By using ToString() method with the format string provided. We can supply a format provider as well (which implements IFormattable) but is not required

var lt = CultureInfo.GetCultureInfo(“lt-LT”); // using System.Globalization;
Console.WriteLine(300.ToString(“C”, lt));
// result: 300,00 €

28
Q

What does the NumberStyles and DateTimeStyles do?

A

They control how parsing works e.g. they let you specify such things as whether parentheses or a currency symbol can appear in the input string (if user does not specify that, a exception is thrown) :

int error = int.Parse(“(2)”); // Exception
int two = int.Parse(“(2)”, NumberStyles.Integer | NumberStyles.AllowParentheses); // Success
int three = double.Parse(“$5.20”, NumberStyle.Currency, CultureInfo.GetCultureInfo(“en-EN”)); // Success 5.20

29
Q

List a couple of standart numeric format strings

A

P : 0.503 => 50.30%
D5: 123 => 00123 (pads left)

30
Q

Name a couple of standart numeric format strings

A

F2: 123.4567 => 123.45
C: 123.3 => $ 123.30
P: 0. 804 => 80.40%

31
Q

What all base types have in common which are able to convert items to other base types?

A

They all implement IConvertable. In most case the implementation for each of these methods simply calls a method in Convert.

32
Q

What is the difference between explicit cast from double to int and using Convert.ToInt32()

A

The main difference that when using explicit cast we are truncating the number, meaning be are leaving behind all the data that do not fit, while Convert method rounds the number to our desirable form.

33
Q

What is a Base-64 convertion?

A

Convert.ToBase64String is a method in the System.Convert class in .NET that is used to convert binary data into a string representation that can be safely transmitted in various contexts, such as over the internet, in a database, or in a file.

The method works by taking binary data, such as an image or a file, and dividing it into groups of 6 bits. Each group of 6 bits is then used to index into a table of 64 characters, which includes the upper- and lower-case letters of the alphabet, digits, and some special characters. The resulting string consists of the characters from the table that correspond to the groups of 6 bits. This string can be transmitted, stored, or manipulated in various ways, and then converted back into the original binary data using the Convert.FromBase64String method.

The use of a table of 64 characters and groups of 6 bits allows for a high degree of data compression, and ensures that the resulting string contains only characters that are safe to use in a variety of contexts. The use of base 64 encoding is widely used in various technologies, such as email, HTTP, and JSON, to transmit binary data in a safe and efficient manner.

34
Q

What is a Globalization?

A

In simple terms, globalization in C# is the process of making a software application usable by people around the world, taking into account the cultural and linguistic differences among them.
In C#, globalization can be achieved through the use of various classes and libraries in the .NET framework, such as the System.Globalization namespace. This namespace provides support for various cultural and linguistic differences, such as the format of dates, times, and numbers, as well as the display of text in different languages and scripts. By using these classes and libraries, a C# application can be designed to adapt its behavior and presentation to the cultural and linguistic preferences of users, regardless of where they are located in the world.

35
Q

What is a Localization?

A

Localization is the process of adapting a software application to meet the specific requirements of a particular country or region. This can be done after writing a program

36
Q

What is the difference between type “long” and BigInteger?

A

‘long’ and BigInteger are two data types in C# used to represent integers. However, they have some important differences:

Size: long is a 64-bit integer, which means it can represent values ranging from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. BigInteger, on the other hand, is an arbitrarily large integer, which means it can represent values of any size, limited only by the amount of memory available.

Performance: long is a built-in data type and is generally faster than BigInteger because it can be processed directly by the computer’s processor. BigInteger, on the other hand, is implemented as a class and its operations are performed using software algorithms, which can be slower than operations performed directly by the processor.

Precision: long has a fixed precision of 64 bits, which means it cannot represent values larger than 9,223,372,036,854,775,807. BigInteger, on the other hand, has an arbitrary precision, which means it can represent values of any size.

In conclusion, long is faster and more efficient than BigInteger when working with values that can be represented within its range, but BigInteger is more flexible and can handle larger values. When choosing between long and BigInteger, it’s important to consider the size of the values you will be working with and the performance requirements of your application.

37
Q

What are the differences between the “Half” “double” and “float”?

A

Half, float, and double are three data types in C# used to represent floating-point numbers. However, they have some important differences:

Size: Half is a 16-bit floating-point number, float is a 32-bit floating-point number, and double is a 64-bit floating-point number. This means that double can represent a wider range of values and has more precision than float, which in turn has more precision than Half.

Precision: Half has a precision of about 5 to 10 significant digits, float has a precision of about 7 to 9 significant digits, and double has a precision of about 15 to 17 significant digits. This means that double is the most precise of the three, followed by float and Half.

Performance: Half is generally faster than float and double because it requires less memory and processing power. float and double are slower than Half but have greater precision.

Range: Half can represent values ranging from about 6.1 x 10^-5 to 6.5 x 10^14. float can represent values ranging from about 1.5 x 10^-45 to 3.4 x 10^38. double can represent values ranging from about 5.0 x 10^-324 to 1.7 x 10^308.

In conclusion, when choosing between Half, float, and double, it’s important to consider the precision and range of the values you will be working with, as well as the performance requirements of your application. Half is the fastest and has the smallest range, but has the least precision. double is the slowest and has the largest range, but has the most precision. float is a good balance between speed, range, and precision.

38
Q

What are the differences between the “Half” “double” and “float”?

A

Half, float, and double are three data types in C# used to represent floating-point numbers. However, they have some important differences:

Size: Half is a 16-bit floating-point number, float is a 32-bit floating-point number, and double is a 64-bit floating-point number. This means that double can represent a wider range of values and has more precision than float, which in turn has more precision than Half.

Precision: Half has a precision of about 5 to 10 significant digits, float has a precision of about 7 to 9 significant digits, and double has a precision of about 15 to 17 significant digits. This means that double is the most precise of the three, followed by float and Half.

Performance: Half is generally faster than float and double because it requires less memory and processing power. float and double are slower than Half but have greater precision.

Range: Half can represent values ranging from about 6.1 x 10^-5 to 6.5 x 10^14. float can represent values ranging from about 1.5 x 10^-45 to 3.4 x 10^38. double can represent values ranging from about 5.0 x 10^-324 to 1.7 x 10^308.

In conclusion, when choosing between Half, float, and double, it’s important to consider the precision and range of the values you will be working with, as well as the performance requirements of your application. Half is the fastest and has the smallest range, but has the least precision. double is the slowest and has the largest range, but has the most precision. float is a good balance between speed, range, and precision.

39
Q

Can Random class be used in security?

A

No. Random is not considered random enough for high-security applications such as cryptohraphy. For this purpose .NET provides cryptographically strong random number generator in the System.Security.Cryptography
RandomNumberGenerator.Create()

40
Q

What is System.Numerics.BitOperations class used for?

A

It exposes the methods to help with base-2 operations (IsPow2, Log2, PopCount, RoundUpToPowerOf2 etc.)

41
Q

What does Type unification in Enums mean?

A

It means that you can implicitly cast any enum member to a System.Enum instance:
Display(Nut.Macadamie) // Nut.Macadamia
Display(Size.Large) // Size.Large

Display(Enum enum){
cw(enum.GetType().Name + “.”+enum.ToString());

42
Q

What are the ways to represent enum values?

A
  1. as a underlying integral value
  2. as an enum member
  3. as a string
43
Q

How could we return an enum integral value from method?

A

static int GetIntegralValue (Enum enum){
return (int) (object) enum; }
//Note double cast
or enum.ToString(“D”) // D is for emiting underlying integral value as string

44
Q

What is the difference between GetValues() and GetNames() in enums?

A

GetValues returns array with all members of a particular enumtype, and GetNames returns the same result but in the form of string array

45
Q

What kind of equalities do you know? When is it used (presume as not overriden)?

A
  1. Value equality - Two values are equivalent in some sence - value types use value equality
  2. Referential equality - Two references refer to the exactly the same object - Reference types use referential equality (This is overriden with anonymous types and records)

Value types can ONLY use value equality (unless boxed)
DateTImeOffset refer to the same point in time
Structs use structural equality - two values are considered equal if all of their members are equal

46
Q

What the objects (types) can use for equality comparison implementation?

A
  1. The == and != operators (compile-time decision – faster than Equal, does not break if null is served (as virtual Equal()))
    object x == object y // False
  2. virtual Equals method in objects System.Objects (available to all types) (runtime decision – looks at actual object type and performs suitable comparison)
    object x == object y // True
  3. IEquatable<T> interface (also has Equals() )</T>
47
Q

What is IEquatable<T> interface is for?</T>

A

Its idea is to give the same result as calling objects virtual Equals method - but more quickly. Its does not use boxing before comparing
~~~
class Test<T> where T : IEquatable<T>
{
public bool IsEqual(T a, T b){
return a.Equals(b); // No boxing with generic T
}
}
~~~
By using `IEquatable<T>`, you can simplify equality comparisons in your code, and improve performance by avoiding unnecessary calls to the `object.Equals(object obj)` method. Additionally, you can also provide a more meaningful definition of equality for your type, which can help make your code more readable and maintainable.</T></T></T>

48
Q

How to override equality semantics with classes and structs?

A
  1. Override GetHashCode() and Equals()
  2. Optionally - overload == and !=
  3. Optionally - implement IEquatable<T></T>
49
Q

What is a hashtable?

A

A collection for which each element has a key used for storage and retrieval. A hashtable applies a very specific strategy for efficiently allocating elements based on their key. This requires that each key have an Int32 number or a hashcode (unique code)

50
Q

What are the axioms for overriding object.Equals() ?

A
  • an object cannot equal null (unless its a nullable type)
  • equality is reflexive (an object equals itself)
  • equality is communicative (if a.Equals(b) then b.Equals(a))
  • equality is transitive (if a.Equals(b) and b.Equals(c) then a.Equals(c))
  • Equality operations are repeatable and reliable (they don’t throw exceptions)
51
Q

What is the IComparable used for?

A

IComparable interfaces are used by general-purpose sorting algorithms

52
Q

After the used of a.CompareTo(b) a number was returned - what does it mean?

A
  • positive number: a comes after b
  • 0 is returned: a is the same as b
  • negative number: a comes after b
53
Q

How do the Equal works differently than IComparable interface?

A

Firstly they return different kind of values Equals: true/false, CompareTo: numbers
Equals is more picky than CompareTo, meaning if the CompareTo returns 0 as if “objects looks the same” Equals can return false because for example the actual ASCII value of the letter is not the same as the other value

54
Q

With which commands can you reach environmental variables?

A

GetEnvironmentalVariable, GetEnvironmentalVariables and SetEnvironmentalVariable

55
Q

What does the FailFast command do?

A

Immediately terminates the program without performing cleanup

56
Q

What can you do with UseShellExecute?

A
  1. Specify a path to a file or document rather than an executable (resulting in the operating system opening the file or document with its associated application)
  2. Specify a URL (resulting in the operating system navigating to that URL in the default web browser)
  3. (Windows only) Specify a Verb (such as ‘runas’ to run the process with administrative elevation)
57
Q

Name two properties of AppContext and what do they do?

A
  1. BaseDirectory - returns the folder in which the application started. This folder is important for assembly resolution (finding and loading dependencies) and locating configuration files (such as appsettings.json)
  2. TargetFrameworkName - tells you the name and version of the .NET runtime that the application targets (as specified in its .runtimeconfig.json file). This might be older than the runtime actually in use

Also AppContext class manages a string-keyed dictionary of Boolean values, intended to offer library writers a standard mechanism for allowing consumers to switch new features on or off:
AppContext.SetSwitch(“MyLibrary.SomeNewFeature”, true);
—-
bool isDefined, switchValue;
isDefined = AppContext.TryGetSwitch(“MyLibrary.SomeNewFeature”, out switchValue);