📜 ⬆️ ⬇️

Tricky C # Questions


I want to bring to your attention the comic purchase tricky questions on C #.
I could not resist and decided to post some classics.
Some questions in the compilation of someone may seem too simple, but a small catch in them, as a rule, is. Sometimes you can catch a simple question. Will be useful to those who study the language.
All who are interested, please under the cat!

1 What will be the result of the following code?

static String str; static DateTime time; static void Main(string[] args) { Console.WriteLine(str == null ? "str == null" : str); Console.WriteLine(time == null ? "time == null" : time.ToString()); Console.ReadLine(); } 

Answer
str == null
1/1/0001 12:00:00 AM
Both variables are not initialized, but string is a reference / reference type (to be more precise, it is immutable type, which means reference type with value type semantics), and DateTime is type of value. The default value for an uninitialized DateTime type is 12:00 AM on January 1 of 1 year.


2 Let's play with inheritance. What will be displayed on the screen?
')
  class A { public void abc(int q) { Console.WriteLine("abc  A"); } } class B : A { public void abc(double p) { Console.WriteLine("abc  B"); } } static void Main(string[] args) { int i = 5; B b = new B(); b.abc(i); Console.ReadLine(); } 

Answer
abc from B


3 Similar question. What will be the result?

  class P { } class Q : P { } class A { public void abc(Q q) { Console.WriteLine("abc  A"); } } class B : A { public void abc(P p) { Console.WriteLine("abc  B"); } } static void Main(string[] args) { B b = new B(); b.abc(new Q()); Console.ReadLine(); } 

Answer
abc from B
Here everything is a little more obvious compared to the previous example.


4 Typical "divorce" on the understanding of polymorphism. The main thing do not forget and do not lose sight of.
What will be the result of the following code?

  class Program { static void Main(string[] args) { MyClassB b = new MyClassB(); MyClassA a = b; a.abc(); Console.ReadLine(); } } class MyClassA { public MyClassA() { Console.WriteLine("constructor A"); } public void abc() { Console.WriteLine("A"); } } class MyClassB:MyClassA { public MyClassB() { Console.WriteLine("constructor B"); } public void abc() { Console.WriteLine("B"); } } 

Answer
constructor A
constructor B
A
When class B is initialized, the class A default constructor will be executed, then the class B constructor. After assigning the class B type variable to the value b, we will get an instance of class B in it. It would seem that abc () from class B should be called, but since B does not specify any predicate of the abc method, then it turns out that it hides abc from class A. The example is not entirely correct and abc () in class B will be emphasized, since the predicate new is required.


5 I have such a class:

  public class Point { public int X { get; set; } public int Y { get; set; } public Point(int xPos, int yPos) { X = xPos; Y = yPos; } } 

And there are 3 instances of the class. Will similar third instance initialization work? If not, what should be done?

  Point ptOne = new Point(15, 20); Point ptTwo = new Point(40, 50); Point ptThree = ptOne + ptTwo; 

Answer
An example will not work, of course. In order for this code to work, you must add an overload of the addition operator to the class Point. For example, like this:

  public static Point operator +(Point p1, Point p2) { return new Point(p1.X + p2.X, p1.Y + p2.Y); } 



6 What will be the result of the following code?

  string result; private async void btnStart_Click(object sender, RoutedEventArgs e) { SaySomething(); txtSomeTextBlock.Text = result; } async System.Threading.Tasks.Task<string> SaySomething() { await System.Threading.Tasks.Task.Delay(1000); result = "Hello world!"; return result; } 

Answer
An empty string will be displayed, not “Hello world!”. Task SaySomething () was called without await and therefore SaySomething is executed synchronously before the first await, that is, before the string

 await System.Threading.Tasks.Task.Delay(1000); 

Then execution returns to btnStartClick. If you use await when calling SaySomething (), the result will be expected and the text “Hello world!” Will be displayed


7 Question from the category of "must know". What will be the result of the following code?

  delegate void SomeMethod(); static void Main(string[] args) { List<SomeMethod> delList = new List<SomeMethod>(); for (int i = 0; i < 10; i++) { delList.Add(delegate { Console.WriteLine(i); }); } foreach (var del in delList) { del(); } } 

Answer
The program will display the number 10 ten times.
Delegate was added 10 times. And the reference to the variable i was taken. Link, not value. That is why when the delegate is called, the last value of the variable i is taken. This is a typical closure example.


8 What will the following code display?

  static bool SomeMethod1() { Console.WriteLine(" 1"); return false; } static bool SomeMethod2() { Console.WriteLine(" 2"); return true; } static void Main(string[] args) { if (SomeMethod1() & SomeMethod2()) { Console.WriteLine(" if "); } } 

Answer
Method 1
Method 2
The if block will not be executed, because SomeMethod1 returns false. But, since the logical operator is used &, the second condition - SomeMethod2 will be checked. If the more familiar && operator were used, then only the value of the first method would be checked.


9 Another simple (you can even say bearded) question. What will be the result of the following code?

  double e = 2.718281828459045; object o = e; // box int ee = (int)o; 

Answer
This code will not work and will throw an exception in the last line. Although it would seem that the next casting (casting or otherwise, explicit conversion) does not cause an error, but only loses the fractional part of the number.

  double e = 2.718281828459045; int ee = (int)e; 

But when unboxing, it checks whether the object contains the value of the requested type. And only after this check, the value is copied to the variable.
But the next one will do unboxing without an error.

  int ee = (int)(double)o; 

The following code will also first cast the object o to the type dynamic and then without problems will perform casting, not unboxing:

  int ee = (int)(o as dynamic); 

However, it is equivalent to the following code:

  int ee = (int)(o is dynamic ? (dynamic)o : (dynamic)null); 

and as a result, will actually be identical to the first example:

  int ee = (int)(dynamic)o; 

although it would seem to be a new trick.


10 What will happen as a result of the execution of this code?

  float q = float.MaxValue; float w = float.MaxValue; checked { float a = q * w; Console.WriteLine(a.ToString()); } 

Answer
The screen will display:
Infinity
float and double are not integral types and therefore there is no overflow in the case of checked. Although if we used int, byte, short or long, then an error would be expected. Unchecked will also not work with non-built-in types. For example:

  decimal x = decimal.MaxValue; decimal y = decimal.MaxValue; unchecked { decimal z = x * y; Console.WriteLine(z.ToString()); } 

Throws a System.OverflowException exception.


11 You can still play with the type decimal. If something is displayed, then what?

  int x = 5; decimal y = x / 12; Console.WriteLine(y.ToString()); 

Answer
This example will output 0 because x is too lazy to lead to the decimal type. Since x is an integer type, dividing 5 by 12 yields a number less than 1, which means that it is an integer zero. The correct result will display the line:

  decimal y = (decimal)x / 12; 



12 What happens as a result of the following code:

  double d=5.15; d = d / 0; float f = 5.15f; f = f / 0; decimal dc = 5.12m; dc = dc / 0; 

Answer
Dividing by 0 types double and float will return Infinity, but decimal will cause a System.DivideByZeroException exception.

Just in case, briefly about the differences between decimal, double and float:
decimal (128-bit data type, accuracy 28–29 decimal places) - used in financial calculations that require high accuracy and no errors when rounding
double (64-bit data type, 15–16 decimal places) is a common type for storing floating point values. Used in most cases (except financial)
float (32-bit data type, accuracy of 7 decimal places) - the type with the lowest accuracy and the lowest range, but with the highest performance. Errors may occur when rounding. Used for high load calculations.


13 Suppose there is such a method:

 int SomeMethod(int x, int y) { return (x - y) * (x + y); } 

Can I call it like this:

 SomeMethod(y:17, x:21) 

Answer
Yes you can. You can still call it like this:

 SomeMethod(11, y:27) 

But not like this:

 SomeMethod(x:12, 11) 

UPDATE: Starting from C # 7.2, making such a call is likely to be possible.


14 What will happen as a result of the execution of this code?

  static void Main(string[] args) { int someInt; SomeMethod2(out someInt); Console.WriteLine(someInt); SomeMethod1(ref someInt); Console.WriteLine(someInt); SomeMethod(someInt); Console.WriteLine(someInt); Console.ReadLine(); } static void SomeMethod(int value) { value = 0; } static void SomeMethod1(ref int value) { value = 1; } static void SomeMethod2(out int value) { value = 2; } 

Answer
Nothing bad will happen. Will be displayed on the screen:
2
one
one
Since we are the first to call SomeMethod2 with the out keyword, it means that someInt can be transferred without initialization. If we used SomeMethod or SomeMethod1, there would be a compilation error.
Since SomeMethod in the parameter does not contain the keyword ref or out, the value in this method is passed by value, not by reference, which means someInt does not change.
The keywords ref and out mean that the values ​​are passed by reference. But in the second case, the value of the parameter must be given in the method. In our example, in the SomeMethod2 method, the value parameter must be assigned a value.


15 Does the code work?

  static void Main(string[] args) { goto lalala; int i = 5; { Console.WriteLine(i); } lalala: Console.WriteLine(",  ! (="); Console.ReadLine(); } 

Answer
Yes, even though it looks unusual. Only Farewell to the cruel world will be displayed !
Inside the method, it is quite possible to declare an enclosing local area between curly brackets. Variables from this area will not be available outside of it. That is, such code will not compile:

  static void Main(string[] args) { { int i = 10; } Console.WriteLine(i); } 

Oddly enough, but goto in C # is still supported. Although not really needed.


16 What will be displayed

  string hello = "hello"; string helloWorld = "hello world"; string helloWorld2 = "hello world"; string helloWorld3 = hello + " world"; Console.WriteLine(helloWorld == helloWorld2); Console.WriteLine(object.ReferenceEquals(helloWorld, helloWorld2)); Console.WriteLine(object.ReferenceEquals(helloWorld, helloWorld3)); Console.ReadLine(); 


Answer
It will be displayed: True, True, False
This is a typical example of string interning. Situations when strings storing the same value are one object in memory. This mechanism allows a little more economical use of memory.


17 Is it possible in C # to use pointers as in C ++?

Answer
It is possible inside the method declared with the unsafe modifier or inside the unsafe block

 unsafe {     int a = 15; *b = &a; Console.WriteLine(*b);     } 

It is necessary not to forget to specify “Allow unsafe code” in the project properties.


18 What are verb / strings?

Answer
Everyone knows what the lines are and constantly use them, but not everyone knows the name.
Verbatim strings are strings that begin with the @ character and in which escape sequences are not processed.
How to call them correctly in Russian - verbatim or exact is a separate question.


Bonus:
What is the difference readonly and const?
Can a class have a static constructor?
Can there be a try without catch?

Source: https://habr.com/ru/post/275789/


All Articles