C# interview questions

C# interview questions

Table of contents

General issues

What is the difference between interface-oriented, object-oriented, and aspect-oriented programming?

Aspect-Oriented

Aspect-oriented programming is based on the study of how many and what components or parts are required to interact with the system. The main thing for AOP is the interaction of these elements.

Interface-oriented

Interface-oriented programming is a programming-by-contract approach. No part of the interface depends on how the other is implemented, all communication between them is described in the contract. WSDL-based web services are the best-known example of this approach.

Object-Oriented

Object-oriented programming is based on the concepts of abstraction, encapsulation, polymorphism, and inheritance. Classes implement these concepts to construct the objects that control or implement the system.

Abstraction allows you to reduce the coupling between components by providing an additional layer between them so that one object does not depend on how the other implements its business rules. (Interfaces, layers) Great thing if you want to isolate parts of the system so that changing or replacing them does not become a problem for the operation of the system as a whole.

Encapsulation allows abstraction to work by hiding the implementation details of a class from its callers. (Public and private fields)

Inheritance allows base (parent) classes to contain common functionality and pass it on to all their descendant classes. The Figure class can have a color field, which will be inherited by its Square or Circle descendant classes.

Polymorphism allows public methods of the same name to be implemented, allowing different classes to perform different actions on the same call. That is, objects of classes Square and Circle can be displayed (implement the render method) differently even though they are both subclasses of Shape, the render method is defined in Shape. (overriding)

What is CLR? What is IL? What is CLS?

The CLR ("Common Language Runtime") is a component of the .NET Framework whose main task is to manage the interpretation and execution of IL code. The CLR is responsible for isolating application memory, type checking, code safety, and converting IL to machine code.

IL (Intermediate Language) - code containing a set of platform-independent instructions. In other words, after compiling the source code, it is not converted into code for a particular platform, but into intermediate IL code.

CLS ("Common Language Specification") is a set of rules by which developers achieve conflict-free operation in all .NET languages.

What is managed code?

Managed code is code that runs in the CLR. Contains metadata that provides runtime information about types, members, and references used in code.

What is assembly?

Assembly (assembly) - one or more files containing a logical set of functionality (code and other data associated with the code). There are static assemblies, which are stored on disk, and dynamic assemblies, which are created during program execution. An assembly is the basic block of an application, all resources related to it are available either only inside this block, or are exported outside. At run time, the assembly sets the name scope and enforces it.

What are private and shared builds?

Assembly (assembly) are of two types - private (private), which uses only the application itself, and joint (shared), used by a set of applications. With private builds, the application is isolated from the external influ## ence of programs and the operating system, there is no need to worry about the uniqueness of names in the global namespace. To make an assembly collaborative, it must be assembled specially and given a strongly encrypted name.

What is an assembly manifest?

An assembly manifest is an internal part of an assembly that allows it to be self-describing. The assembly manifest allows you to identify the assembly, specifies the files that are included in the assembly implementation, describes the types and resources used in the assembly, specifies dependencies on other assemblies, and the set of access rights that the assembly needs to work correctly. This information is used at runtime to resolve references, validate versions, and check the integrity of loaded assemblies.

What is the difference between namespace and assembly concepts?

Namespace (namespace) is a logical convention used at design time, while assembly (assembly) sets the scope of the name during execution.

What is the difference between Value Type and Reference Type?

Value Type is on the stack and Reference Type is on the heap.

When is object garbage collected?

An object is garbage collected when it is no longer referenced.

What is Code Access Security (CAS)?

CAS is a security technology that allows you to set a limit on the execution of managed code. In this way, you can define permissions and set access rights to computer resources.

What is an attribute?

An attribute (attribute) is a universal means of linking data with types; they allow you to add any textual information about classes, properties, methods, etc. Attributes are stored with metadata and can be retrieved when the program is executed.

How do ensure the use of named parameters in an attribute constructor?

Attribute constructors can take named parameters - attribute fields and properties. When a named parameter is specified, the attribute constructor is passed the name of the property or field that should accept the parameter. At what these properties and fields should be open. If named parameters are passed, they must follow the positional parameters that are explicitly specified in the attribute's constructor. Specifying named parameters is optional, so when designing attributes, you need to remember that some of their fields or properties may not be initialized. An example of using named parameters in an attribute constructor:

[DllImport("Kernel32", CharSet=CharSet.Auto, SetLastError=true)]

Here, 1 positional parameter is passed - the string "Kernel32" and 2 named parameters that set the public fields CharSet and SetLastError to CharSet.Auto and true respectively.

What is the difference between Finalize and Dispose?

Dispose provides explicit control over the resources used by the object, while Finalize is implicit, used by the garbage collector.

What are boxing and unboxing?

Boxing allows you to convert a value type to a reference type. When packing a value type object, the following actions occur:

  • Memory is allocated on the managed heap.
  • The fields of the value type are copied into the memory that was allocated on the heap.
  • The address of the object is returned.

Some compilers automatically generate the IL required to box a value type object. The process of extracting field addresses from a boxed object is called unboxing. Unpacking is not the exact opposite of packaging. Unlike packaging, no copying occurs during unpacking. However, unpacking is usually followed by field copying, so both operations (unpacking and copying) are the opposite of the boxing operation. Here is an example of using packing and unpacking.

structPoint {
    public Int32 x, y;
}

class app {
    static void Main() {
       ArrayList a = new ArrayList();
       Point p; // Allocate memory for the Point (not on the heap).
       for (Int32 i = 0 ; i < 10; i++) {
          p.x = p. y = i; // Initialize the members in our value type.
          a.Add(p); // Boxing the value type and adding a reference to the ArrayList.
}

 Point p1 = (Point) a[0]; // unpacking and copying fields
}

Packing and unpacking/copying reduces the performance of the application both in terms of slowdown and additional memory consumption, so you should try to minimize the creation of code in which the operations of packing and unpacking/copying occur.

What is GAC?

GAC is the global assembly cache. It stores shared assemblies. This is usually C:\Windows\Assembly\GAC. This directory has a certain structure, which stores subdirectories whose names are generated according to a certain algorithm. Only strongly named assemblies can be placed in the GAC. To place an assembly in the GAC, use the special tool GACUtil.exe, which knows the entire internal structure of the GAC and can generate subdirectory names properly. Registering assemblies in the GAC is necessary to avoid assembly name conflicts. Let's take an example: two companies released an assembly and called it the same name Calculus. If we copy this assembly to a directory that already contains an assembly with the same name, then we will overwrite an assembly that may have previously been used by some application. This application with the new assembly will no longer be able to work. The solution to this problem is to register these two assemblies in the GAC, in which a separate directory will be created for each.

What types can be used in a foreach clause?

Arrays, collections. Classes that implement the System.Collections.IEnumerable interface.

What is the difference between a class and a struct?

For C#, the classes System.Object, System.Exception, System.File-Stream, and System.Random are reference types (memory is allocated from the control heap). In turn, dimensional types in the documentation are called structures (structure) and enumerations (enumeration). For example, the System.In132, System.Boolean, System.Decimal, System.TimeSpan structures, and the System.DayOfWeek, System.10.FileAttributes, and System.Drawing.FontStyle enumerations are value types (stored normally on the thread stack, but can be embedded in reference types).

What does the virtual modifier mean?

When inheriting a class. This method can be overridden in derived classes with the override keyword.

What is the difference between an event and a delegate?

A delegate is essentially a function pointer.

In C#, the publisher-subscriber model is where a class publishes an event that it can raise, and any classes can subscribe to that event. The method to be called when the event occurs is defined by the delegate

Can a class implement two interfaces that have the same methods declared? How?

public class GiuseppePizzaria : IWindow, IRestaurant
{
    // Implementation of the GetMenu method of the IWindow interface.
    Object IWindow.GetMenu() { ... }
    // Implementation of the GetMenu method of the IRestaurant interface.
    Object IRestaurant.GetMenu() { ... }
}

Does C# support multiple inheritances?

C# supports multiple inheritances in the form of inheritance from a class and multiple interfaces, or just from multiple interfaces.

But it does not support inheritance from multiple classes.

Who can access protected variables at the class level?

Any derived class

Are variables inherited with the private modifier?

Yes, but they are not available.

Describe the “protected internal” modifier Members with this modifier are available to classes that are in the same assembly and inherit from this class.

What is the name of the .NET class that all classes inherit from?

System.Object.

What does the term immutable mean?

This means that the data stored in the variable cannot be changed. In doing so, note that the value of a variable can be changed - by not using old data that can be changed. The original data remains in memory, and new values ​​are created again in a new memory area. An example is the String type.

What's the difference between the System.String and System.Text.StringBuilder classes?

The data stored in the System.String class is immutable. The System.StringBuilder class was designed so that a variety of operations can be performed on a mutable string. That is, with each operation on an object of the System.String class, data is transferred to a new memory area, which affects the performance of the program.

What is the advantage of using the System.Text.StringBuilder class over System.String?

The StringBuilder class is more efficient when dealing with a large number of strings. Objects of the System.String class is immutable, so each time the string changes, a new object is created in memory.

Is it possible to store different types of data in an object of class System.Array?

static void Main(string[] args) 
{
    object[] arr = new object[] { "string", 0, new Guid() };
    foreach (object var in arr)
    {
        Console.WriteLine(var.GetType().ToString());
    }
    Console.ReadKey();
     double d = 0.0;
    ValueType[] arr2 = new ValueType[] { d, 0, new Guid() };
    foreach (ValueType var in arr2)
    {
        Console.WriteLine(var.GetType().ToString());
    }
    Console.ReadKey();
}

Explain the difference between System.Array.CopyTo() and System.Array.Clone()?

The first operation performs a deep copy of the array, and the second one is shallow. Shallow copying of an array only copies the elements of an Array object, whether they are reference types or value types. Objects referenced by reference types are not copied. The references in the new Array object point to the same objects as the references in the original Array. A deep copy copies both the elements of the Array class and the objects they refer to explicitly or implicitly.

How to sort array elements in descending order?

You need to call the Sort() method and then the Reverse() method.

As, is - what is it, how is it applied?

With the as an operator, the program tries to convert an expression to a specific type without throwing an exception. If the conversion fails, the expression will contain null.

The expression o is Employee tests whether the variable o is an object of type Employee.

Type casting operators.

If(o is Employee){

Employee e = (Employee) o;

}

What is the difference between throw ex; and throw;?

throw re-throws the exception that was encountered and saves the stack trace (path to the source of the exception). throw ex throws the same exception but resets the stack trace to the method where throw ex is done.

How does return work in try-catch-finally?

The algorithm is something like this:

  • The code before the return statement is executed;
  • The expression in return is evaluated
  • The finally block is executed
  • Returns the result calculated in step 2

Consider the following code:

public static async Task Main()
        {
            Console.WriteLine(MyMethod().Text);
            Console.ReadKey();
        }

        public static TestClass MyMethod()
        {
            var number = new TestClass
            {
                Text = "5"
            };
            try
            {
                return number;
            }
            catch
            {
                number.Text = "haha";
                return number;
            }
            finally
            {
                number.Text = "finally";
            }
        }

What will we get on the screen?

finally

why is that? We did not change the result that was obtained in step 2, we changed the value of the property of the reference type, but did not change the object itself

If we rewrite the finally block like this:

...
finally
{
   number = new TestClass {Text = "finally"};
}

we will get the answer

5

If we do this with a value type, the result is the same. That is, in the finally block, you cannot change the returned object, but you can change the properties of the object.

Questions by class

What is the syntax for specifying a parent class in C#?

After the class name of the inheritor, you need to put a colon and specify the name of the base class. Example:

class ChildClass : ParentClass

Is it possible to forbid inheritance from your class?

Yes. The keyword “sealed” is used for this.

Is it possible to allow class inheritance but prevent method overriding?

Yes. Specify the class as public and the method as sealed.

What is an abstract class?

This is a class whose object cannot be instantiated. Such a class must have a descendant class with the implementation of abstract methods. An abstract class is a blueprint of a normal class with no implementation.

When are you required to declare a class abstract?

If the class is a descendant of an abstract class, not all methods of the base class are overridden and have an implementation. If at least one class method is abstract.

What is a class interface?

Interfaces, like classes, define a set of properties, methods, and events. But, unlike classes, they do not contain their implementation. Interfaces are implemented by classes and are defined as independent entities.

Why can't you specify a visibility modifier for interface methods?

Because all of them must have the public modifier, which is set by default.

Is it possible to inherit from multiple interfaces?

Yes.

What is the difference between an interface and an abstract class?

In an interface, all methods (properties, etc.) are abstract and have no implementation. In an abstract class, some methods can be implemented. In an interface, members cannot have a visibility modifier (they are all public by default), but in an abstract class, members can have a visibility modifier.

Name the differences between structures and classes.

For C#, the classes System.Object, System.Exception, System.File-Stream, and System.Random are reference types (memory is allocated from the control heap). In turn, dimensional types in the documentation are called structures (structure) and enumerations (enumeration). For example, the System.In132, System.Boolean, System.Decimal, System.TimeSpan structures, and the System.DayOfWeek, System.10.FileAttributes, and System.Drawing.FontStyle enumerations are value types (stored typically on the thread stack, but can be embedded in reference types).

What is the difference between abstract and virtual classes? Between virtual and abstract methods?

An abstract class is a class that contains at least one method (abstract). A virtual method has an implementation and can. overridden in a derived class. An abstract method has no implementation, only a description of the method that should be. implemented in derived classes.

Dispose(), Finalize() - what are these methods, how are they used in .NET?

Used to free resources. When using the Dispose method, you must provide implicit cleanup with the Finalize method. If the programmer failed to call the Dispose method, using the Finalize method prevents a permanent resource leak.

What is the using(…){…} construct in .NET for? What about IDisposable?

The value of Using is directly related to the IDisposable interface. The IDisposable interface gives us the ability to quickly release shared resources without relying on an automatic garbage collector. The Using construct allows you to call the Dispose method automatically as soon as the desired object leaves the Using block.

Questions about methods and properties

What is the explicit name of the parameter passed to the set method of the class property?

value. The type of this parameter is determined by the type of the property.

What does the "virtual" keyword mean for a method or property?

That a method or property can be overridden.

How is an overridden method different from an overloaded method?

When we override a method, we change its behavior in the derived class. Overloading a method simply results in the use of another method of the same name within the class.

Can an overridden method be declared static if the overridden method is not static?

No. The signature of a virtual method must remain constant, except for the replacement of the virtual keyword with the override keyword.

Assembly questions

What is a "satellite assembly"?

Assemblies marked with specific locales are called satellite assemblies

What is the smallest executable unit in .NET?

Assembly

What happens in memory when boxing and unboxing a value type?

When you box an instance of a value type, the following happens.

  • Memory is allocated on the managed heap. Its scope is determined by the length of the value type and some overhead to allow the value type to become a true object. This overhead is the method table pointer and the SyncBlockIndex index.

  • The fields of the value type are copied into the memory just allocated on the heap.

  • The address of the object is returned. This address is a reference to an object; the dimension type has become a reference type.

Unpacking is not the exact opposite of packaging.

It consists only in obtaining a pointer to the source.

the value type (data fields) contained in the object. And no copying when unpacking (as opposed to packaging). However, usually after unpacking, fields are copied, so the sum of both these operations is a reflection of the boxing operation.