DETAILED READ SECTION

C# Interview Questions

Question: What is C#?

Answer:

C# is a computer programming language. C# was created by Microsoft in 2000 to provide a modern general-purpose programming language that can be used to develop all kinds of software targeting various platforms including Windows, Web, and Mobile using just one programming language. Today, C# is one of the most popular programming languages in the world. Millions of software developers use C# to build all kinds of software.

  • C# is the primary language for building Microsoft .NET software applications. Developers can build almost every kind of software using C# including Windows UI apps, console apps, backend services, cloud APIs, Web services, controls and libraries, serverless applications, Web applications, native iOS and Android apps, AI and machine learning software, and blockchain applications.


Question: Tell advantages of using C#?

Answer:

  • C# with the help of Visual Studio IDE, provides a rapid application development. C# is a modern, object-oriented, simple, versatile, and performance-oriented programming language. C# is developed based on the best features and use cases of several programming languages including C++, Java, Pascal, and SmallTalk.

  • C# syntaxes are like C++. .NET and the C# library is similar to Java. C# supports modern object-oriented programming language features including Abstraction, Encapsulation, Polymorphism, and Inheritance. C# is a strongly typed language and most types are inherited by the Object class.

  • C# supports concepts of classes and objects. Classes have members such as fields, properties, events, and methods. Here is a detailed article on C# and OOP.


Question: What is an object in C#?

Answer:

C# language is an object-oriented programming language. Classes are the foundation of C#. A class is a template that defines what a data structure will look like, and how data will be stored, managed, and transferred. A class has fields, properties, methods, and other members.

While classes are concepts, objects are real. Objects are created using class instances. A class defines the type of an object. Objects store real values in computer memory.

Any real-world entity which has some certain characteristics or that can perform some work is called an Object. This object is also called an instance, i.e. a copy of an entity in a programming language. Objects are instances of classes.

For example, we need to create a program that deals with cars. We need to create an entity for the car. Let’s call it a class, Car. A car has four properties, i.e., model, type, color, and size.


To represent a car in programming, we can create a class, Car, with four properties, Model, Type, Color, and Size. These are called members of a class. A class has several types of members, constructors, fields, properties, methods, delegates, and events. A class member can be private, protected, and pubic. Since these properties may be accessed outside the class, these can be public.

An object is an instance of a class. A class can have as many instances as needed. For example, Honda Civic is an instance of Car. In real programming, Honda Civic is an object. Honda Civic is an instance of the class Car. The Model, Type, Color, and Size properties of Honda Civic are Civic, Honda, Red, 4 respectively. BMW 330, Toyota Carolla, Ford 350, Honda CR4, Honda Accord, and Honda Pilot are some more examples of objects of Car.


Question: What is Managed or Unmanaged Code?

Answer:

Managed Code

“Managed code is the code that is developed using the .NET framework and its supported programming languages such as C# or VB.NET. Managed code is directly executed by the Common Language Runtime (CLR or Runtime) and its lifecycle including object creation, memory allocation, and object disposal is managed by the Runtime. Any language that is written in .NET Framework is managed code".


Unmanaged Code

The code that is developed outside of the .NET framework is known as unmanaged code.

“Applications that do not run under the control of the CLR are said to be unmanaged. Languages such as C or C++ or Visual Basic are unmanaged.

The object creation, execution, and disposal of unmanaged code is directly managed by the programmers. If programmers write bad code, it may lead to memory leaks and unwanted resource allocations.”

The .NET Framework provides a mechanism for unmanaged code to be used in managed code and vice versa. The process is done with the help of wrapper classes.


Question: What is Boxing and Unboxing in C#?

Answer:

Boxing and Unboxing both are used for type conversions.


The process of converting from a value type to a reference type is called boxing. Boxing is an implicit conversion. Here is an example of boxing in C#.


// Boxing  

int anum = 123;    

Object obj = anum;    

Console.WriteLine(anum);   

Console.WriteLine(obj);


The process of converting from a reference type to a value type is called unboxing. Here is an example of unboxing in C#.


// Unboxing

Object obj2 = 123;  

int anum2 = (int)obj;  

Console.WriteLine(anum2);  

Console.WriteLine(obj);


Question: What is the difference between a struct and a class in C#?

Answer:

Class and struct are both user-defined data types, but have some major differences:


Struct

  • The struct is a value type in C# and it inherits from System.Value Type.

  • Struct is usually used for smaller amounts of data.

  • Struct can’t be inherited from other types.

  • A structure can't be abstract.

  • No need to create an object with a new keyword.

  • Do not have permission to create any default constructor.

Class

  • The class is a reference type in C# and it inherits from the System.Object Type.

  • Classes are usually used for large amounts of data.

  • Classes can be inherited from other classes.

  • A class can be an abstract type.

  • We can create a default constructor.

Question: What is the difference between Interface and Abstract Class in C#?

Answer:

Here are some of the common differences between an interface and an abstract class in C#.

  • A class can implement any number of interfaces but a subclass can at most use only one abstract class.

  • An abstract class can have non-abstract methods (concrete methods) while in case of interface, all the methods have to be abstract.

  • An abstract class can declare or use any variables while an interface is not allowed to do so.

  • In an abstract class, all data members or functions are private by default while in interface all are public, we can’t change them manually.

  • In an abstract class, we need to use abstract keywords to declare abstract methods, while in an interface we don’t need to use that.

  • An abstract class can’t be used for multiple inheritance while the interface can be used as multiple inheritance.

  • An abstract class use constructor while in an interface we don’t have any type of constructor.


Question: What is enum in C#?

Answer:

An enum is a value type with a set of related named constants often referred to as an enumerator list. The enum keyword is used to declare an enumeration. It is a primitive data type that is user-defined.

An enum type can be an integer (float, int, byte, double, etc.). But if you use it beside int it has to be cast.

An enum is used to create numeric constants in the .NET framework. All the members of enum are enum type. There must be a numeric value for each enum type.

The default underlying type of the enumeration element is int. By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1


enum Day {Sat, Sun, Mon, Tue, Wed, Thu, Fri};


Some points about enum:

  • Enums are enumerated data types in c#.

  • Enums are not for the end-user, they are meant for developers.

  • Enums are strongly typed constant. They are strongly typed, i.e. an enum of one type may not be implicitly assigned to an enum of another type even though the underlying value of their members is the same.

  • Enumerations (enums) make your code much more readable and understandable.

  • Enum values are fixed. Enum can be displayed as a string and processed as an integer.

  • The default type is int, and the approved types are byte, sbyte, short, ushort, uint, long, and ulong.

  • Every enum type automatically derives from System.Enum and thus we can use System.Enum methods on enums.

  • Enums are value types and are created on the stack and not on the heap.


Question: What is the difference between “continue” and “break” statements in C#?

Answer:

Using break statement, you can 'jump out of a loop' whereas by using a continue statement, you can 'jump over one iteration' and then resume your loop execution.


Question: What is the difference between constant and readonly in C#?

Answer:

Const is nothing but "constant", a variable of which the value is constant but at compile time. It's mandatory to assign a value to it. By default, a const is static and we cannot change the value of a const variable throughout the entire program.

Readonly is the keyword whose value we can change during runtime or we can assign it at run time but only through the non-static constructor.


Question: Can “this” be used within a static method?

Answer:

We can't use 'this' in a static method because the keyword 'this' returns a reference to the current instance of the class containing it. Static methods (or any static member) do not belong to a particular instance. They exist without creating an instance of the class and are called with the name of a class, not by instance, so we can’t use this keyword in the body of static Methods. However, in the case of Extension Methods, we can use the functions parameters.


Let’s have a look at the “this” keyword.

The "this" keyword in C# is a special type of reference variable that is implicitly defined within each constructor and non-static method as a first parameter of the type class in which it is defined.


Question: What are Properties in C#?

Answer:

C# properties are members of a C# class that provide a flexible mechanism to read, write or compute the values of private fields, in other words, by using properties, we can access private fields and set their values. Properties in C# are always public data members. C# properties use get and set methods, also known as accessors, to access and assign values to private fields.


We have three types of properties: Read/Write, ReadOnly, and WriteOnly.


Question: What are accessors?

Answer:

The get and set portions or blocks of a property are called accessors. These are useful to restrict the accessibility of a property. The set accessor specifies that we can assign a value to a private field in a property. Without the set accessor property, it is like a readonly field. With the 'get' accessor we can access the value of the private field. In other words, it returns a single value. A Get accessor specifies that we can access the value of a field publically.



Question: What is the difference between the dispose and finalize methods in C#?

Answer:

The finalize and dispose, both methods are used to free unmanaged resources.

Finalize

  • Finalize is used to free unmanaged resources that are not in use, like files, database connections in the application domain and more. These are resources held by an object before that object is destroyed.

  • In the Internal process, it is called by Garbage Collector and can’t be called manual by user code or any service.

  • Finalize belongs to System.Object class.

  • Implement it when you have unmanaged resources in your code, and make sure that these resources are freed when the Garbage collection happens.

Dispose

  • Dispose is also used to free unmanaged resources that are not in use like files, database connections in the Application domain at any time.

  • Dispose explicitly it is called by manual user code.

  • If we need to dispose method so must implement that class by IDisposable interface.

  • It belongs to IDisposable interface.

  • Implement this when you are writing a custom class that will be used by other users.


Question: What is the difference between String and StringBuilder in C#?

Answer:

StringBuilder and string are both used to string values, but both have many differences on the bases of instance creation and also in performance.


String

String is an immutable object. Immutable is when we create string objects in code so we cannot modify or change that object in any operations like insert new value, replace or append any value with existing value in a string object. When we have to do some operations to change string simply it will dispose of the old value of string object and it will create a new instance in memory for hold the new value in string object,

  • It’s an immutable object that holds a string value.

  • Performance-wise, string is slow because it creates a new instance to override or change the previous value.

  • String belongs to the System namespace.

StringBuilder

System.Text.Stringbuilder is a mutable object which also holds the string value, mutable means once we create a System.Text.Stringbuilder object. We can use this object for any operation like insert value in an existing string with insert functions also replace or append without creating a new instance of System.Text.Stringbuilder for every time so it’s using the previous object. That way, it works fast compared to the System.String.

  • StringBuilder is a mutable object.

  • Performance-wise StringBuilder is very fast because it will use the same instance of StringBuilder object to perform any operation like inserting a value in the existing string.

  • StringBuilder belongs to System.Text.Stringbuilder namespace.

Question: What are delegates in C# and the uses of delegates?

Answer:

A Delegate is an abstraction of one or more function pointers (as existed in C++; the explanation about this is out of the scope of this article). The .NET has implemented the concept of function pointers in the form of delegates. With delegates, you can treat a function as data. Delegates allow functions to be passed as parameters, returned from a function as a value and stored in an array. Delegates have the following characteristics:

  • Delegates are derived from the System.MulticastDelegate class.

  • They have a signature and a return type. A function that is added to delegates must be compatible with this signature.

  • Delegates can point to either static or instance methods.

  • Once a delegate object has been created, it may dynamically invoke the methods it points to at runtime.

  • Delegates can call methods synchronously and asynchronously.

The delegate contains a couple of useful fields. The first one holds a reference to an object, and the second holds a method pointer. When you invoke the delegate, the instance method is called on the contained reference. However, if the object reference is null then the runtime understands this to mean that the method is a static method. Moreover, invoking a delegate syntactically is the exact same as calling a regular function. Therefore, delegates are perfect for implementing callbacks.


Delegates maintain three important pieces of information:

  • The parameters of the method.

  • The address of the method it calls.

  • The return type of the method.

A delegate is a solution for situations in which you want to pass methods around to other methods. You are so accustomed to passing data to methods as parameters that the idea of passing methods as an argument instead of data might sound a little strange. However, there are cases in which you have a method that does something, for instance, invoking some other method. You do not know at compile time what this second method is. That information is available only at runtime, hence Delegates are the device to overcome such complications.


Question: What are sealed classes in C#?

Answer:

Sealed classes are used to restrict the inheritance feature of object oriented programming. Once a class is defined as a sealed class, the class cannot be inherited.

In C#, the sealed modifier is used to define a class as sealed. In Visual Basic .NET the Not Inheritable keyword serves the purpose of the sealed class. If a class is derived from a sealed class then the compiler throws an error.

If you have ever noticed, structs are sealed. You cannot derive a class from a struct.

The following class definition defines a sealed class in C#:


// Sealed class

sealed class SealedClass

{

}


Question: What are partial classes?

Answer:

A partial class is only used to split the definition of a class in two or more classes in the same source code file or more than one source file. You can create a class definition in multiple files, but it will be compiled as one class at run time. Also, when you create an instance of this class, you can access all the methods from all source files with the same object.

Partial Classes can be created in the same namespace. It isn't possible to create a partial class in a different namespace. So use the “partial” keyword with all the class names that you want to bind together with the same name of a class in the same namespace.



Question: What is boxing and unboxing in C#?

Answer:

Boxing and Unboxing are both used for type converting, but have some differences:Boxing

Boxing is the process of converting a value type data type to the object or to any interface data type which is implemented by this value type. When the CLR boxes a value means when CLR converting a value type to Object Type, it wraps the value inside a System.Object and stores it on the heap area in the application domain.


Unboxing

Unboxing is also a process that is used to extract the value type from the object or any implemented interface type. Boxing may be done implicitly, but unboxing has to be explicit by code.


The concept of boxing and unboxing underlies the C# unified view of the type system in which a value of any type can be treated as an object.


Question: What is IEnumerable<> in C#?

Answer:

IEnumerable is the parent interface for all non-generic collections in System.Collections namespace like ArrayList, HastTable etc. that can be enumerated. For the generic version of this interface as IEnumerable<T> which a parent interface of all generic collections class in System.Collections.Generic namespace like List<> and more.

In System.Collections.Generic.IEnumerable<T> have only a single method which is GetEnumerator() that returns an IEnumerator. IEnumerator provides the power to iterate through the collection by exposing a Current property and Move Next and Reset methods, if we don’t have this interface as a parent so we can’t use iteration by foreach loop or can’t use that class object in our LINQ query.


Question: What is the difference between late binding and early binding in C#?

Answer:

Early Binding and Late Binding concepts belong to polymorphism in C#. Polymorphism is the feature of object oriented programming that allows a language to use the same name in different forms. For example, a method named Add that can add integers, doubles, and decimals.


Polymorphism we have 2 different types to achieve that:

  • Compile Time also known as Early Binding or Overloading.

  • Run Time is also known as Late Binding or Overriding.


Compile Time Polymorphism or Early Binding

In Compile time polymorphism or Early Binding, we will use multiple methods with the same name but different types of parameters, or maybe the number of parameters. Because of this, we can perform different-different tasks with the same method name in the same class which is also known as Method overloading.


Run Time Polymorphism or Late Binding

Run time polymorphism is also known as late binding. In Run Time Polymorphism or Late Binding, we can use the same method names with the same signatures , which means the same type or same number of parameters, but not in the same class because the compiler doesn’t allow for that at compile time. Therefore, we can use that bind at run time in the derived class when a child class or derived class object will be instantiated. That’s why we call it Late Binding. We have to create my parent class functions as partial and in driver or child class as override functions with the override keyword