C# Interview Questions

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

What's the Difference between the Is and As operator in C#

"is" operator In C# language, we use the "is" operator to check the object type. If two objects are of the same type, it returns true, else it returns false. "as" operator The "as" operator behaves in a similar way as the "is" operator. The only difference is it returns the object if both are compatible with that type. Else it returns a null.

Which Linq extension retrieves the first object in a returned list or null if the list is empty?

.FirstOrDefault()

Define a Jagged Array in C#?

A Jagged array is referred to as an "array of arrays". It is an array whose elements are arrays, the element of the same can be of different dimensions and sizes. The length of each array index can differ

Illustrate Race Condition?

A Race Condition occurs in a situation when two threads access the same resource and try to change it at the same time. The thread which accesses the resource first cannot be predicted. Let me take a small example where two threads X1 and X2 are trying to access the same shared resource called T. And if both threads try to write the value to T, then the last value written to T will be saved

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

A String is an immutable object. We cannot modify or change that object. We perform operations like replace, append, a new instance of the old string is created which performane wise is slow. Belongs to System namespae A StringBuilder is a mutable object that holds the string value. We can performance string manupliation on this object without creating a new instance bc it's using the same object. Works faster than String. Belongs to System.Text.Stringbuilder namespace

What is Thread Pooling?

A Thread pool is a collection of threads that perform tasks without disturbing the primary thread. Once the task is completed by a thread it returns to the primary thread.

List the difference between the Virtual method and the Abstract method?

A Virtual method must always have a DEFAULT IMPLEMENTATUON. However, it can be overridden in a derived class by the keyword override. An Abstract method DOES NOT HAVE any IMPLEMENTATION. It resides in the abstract class, and also it is mandatory that the derived class must implement abstract class. Use of override keyword is not necessary.

What is a Class?

A class is a blueprint of an object. It defines different kinds of data and functionalities objects will have. A class enables you to create your own custom types by clubbing together variables of different types, methods, and events. In C# a class is defined by a class keyword.

Define Collections?

A collection essentially works like a container for instances of other classes. Every class implements Collection Interface.

Explain Deadlock?

A deadlock is a situation that arises when a process isn't able to complete it's execution because two or more than two processes are waiting for each other to finish. This usually occurs in multi-threading. In this, a shared resource is being held up by a process and another process is waiting for the first process to get over or release it, and the thread holding the locked item is waiting for another process to complete.

What is lambda expressions in C#?

A lambda expression is an anonymous function that you can use to create delegates or expression tree types. By using lambda expressions, you can write local functions that can be passed as arguments or returned as the value of function calls. Lambda expressions are particularly helpful for writing LINQ query expressions. In the following example, the lambda expression x => x * x, which specifies a parameter that's named x and returns the value of x squared, is assigned to a variable of a delegate type:

What is namespace in C#?

A namespace is designed for providing a way to keep one set of names separate from another. The class names declared in one namespace does not conflict with the same class names declared in another. NET uses namespaces to organize its many classes. Declaring your own namespaces can help you control the scope of class and method names in larger programming projects.

How to use Nullable<> Types in C#?

A nullable type is a data type is that contains the defined data type or the null value. Any data type can be declared nullable type with the help of operator "?". For example, the following code declares the int 'i' as a null. int? i = null; This nullable type concept is not compatible with "var". var? i = null; ///will throw error

Define a Partial class?

A partial class is the only one that essentially splits the definition of a class into multiple classes in either same source code files or multiple source code files. One can create a class definition in multiple files but that is compiled as one class at run-time and when an instance of this class is created, one can access all methods from every source file with the same object. It is indicated by the keyword 'partial'. Partial Classes can be created in the same namespace. It isn't possible to create a partial class in a different namespace.

Define an Escape Sequence, Name few strings in Escape Sequence?

An Escape Sequence is denoted by a backslash (). The backslash merely indicates that the character it is following should be interpreted literally or is a special character. An escape sequence is a single character. Few escape sequences are as follows: n - newline character b - backspace - backlash ' - Single quote " - Double quote

What is enum in C#?

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. By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1. 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. Enums are value types and are created on the stack and not on the heap.

How to use extension methods?

An extension method is a static method of a static class, where the "this" modifier is applied to the first parameter. The type of the first parameter will be the type that is extended. Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.

Distinguish between Array and Arraylist in C#?

Array - Array uses the vector array for storing the elements - Size of the Array must be defined until redim used(vb) - An array is a specific data type storage - Typecasting is not necessary - There is no RunTime exception - Elements can't be inserted or deleted in between ArrayList - There's no need for specifying storage size - ArrayList can store everything as an object - Typecasting is necessary - There is a RunTime error exception - Elements can be inserted or deleted in between

What is an IQueryable?

As per MSDN, the IQueryable interface is intended for implementation by query providers. It is only supposed to be implemented by providers that also implement IQueryable<T>. If the provider does not also implement IQueryable<T>, the standard query operators cannot be used on the provider's data source.

Explain Async and Await?

Async and Await keywords are mostly used for creating asynchronous methods in C#. public async Task>CalculateCount() { await Task.Delay(2000); return 1; } public async task mytestmethod() { Task> count = CalculateCount(); int result = await count; } In the above-given code async keyword is used for method declaration. The Count is of a task type int which calls the method CalculateCount(). CalculateCount() starts execution and calculates something.

Difference between the Equality Operator (==) and Equals() Method in C#

Both the == Operator and the Equals() method are used to compare two value type data items or reference type data items. The == Operator compares the reference identity while the Equals() method compares only contents.

What is boxing and unboxing?

Boxing is the process of converting from a VALUE type to a REFERENCE type. Done implicitly. 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 is the process of converting from a REFERENCE type to a VALUE type. Done explicitly by code

What is C#?

C# is a computer programming language. C# was developed 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. 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.

What are Properties in C#?

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.

Explain the process of inheriting a class into another class?

Colon is used as an inheritance operator in C#. Place the colon and the class name. public class Derivedclass: ParentClass

When would you use an Abstract class?

Consider using abstract classes if : - You want to share code among several closely related classes. - You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private). - You want to declare non-static or non-final fields.

When would you use an Interface?

Consider using interfaces if : - You expect that unrelated classes would implement your interface. For example,many unrelated objects can implement Serializable interface. - You want to specify the behaviour of a particular data type, but not concerned about who implements its behaviour. - You want to take advantage of multiple inheritance of type.

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

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.

What is the Constructor Chaining in C#?

Constructor chaining is a way to connect two or more classes in a relationship as Inheritance. In Constructor Chaining, every child class constructor is mapped to a parent class Constructor implicitly by base keyword, so when you create an instance of the child class, it will call the parent's class Constructor. Without it, inheritance is not possible

What are extension methods in C#?

Extension methods enable you to add methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. An extension method is a special kind of static method, but they are called as if they were instance methods on the extended type

How encapsulation is implemented in C#?

Encapsulation is implemented by using access specifiers. An access specifier defines the scope and visibility of a class member. - Public access specifier allows a class to expose its member variables and member functions to other functions and objects. Any public member can be accessed from outside the class. - Private access specifier allows a class to hide its member variables and member functions from other functions and objects. Only functions of the same class can access its private members. Even an instance of a class cannot access its private members. - Protected access specifier allows a child class to access the member variables and member functions of its base class. This way it helps in implementing inheritance.

What is encapsulation?

Encapsulation is the combining of data and code into a single object.

What are Events?

Events in C# follow a concept where it consists of a Publisher, Subscriber, Notification and a handler. You can think of an event as nothing but an encapsulated delegate.

How is Exception Handling implemented in C#?

Exception handling is done using four keywords in C#: try - Contains a block of code for which an exception will be checked. catch - It is a program that catches an exception with the help of exception handler. finally - It is a block of code written to execute regardless whether an exception is caught or not. throw - Throws an exception when a problem occurs.

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

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 is explicitly called by manual user code. - If we need to use the dispose method, we must implement that class via IDisposable interface. - It belongs to IDisposable interface. - Implement this when you are writing a custom class that will be used by other users.

Explain Generics in C#.NET?

Generics are used to make reusable code classes which decrease the code redundancy Increase type safety, performance, and optimization Using Generics one can do a variety of things like create collections To create Generic collection, System.namespace The generic namespace should be used inspite of classes such as ArrayList in the System Generics instigates the usage of a parameterized type

What is the difference between IEnumerable and IQueryable?

IEnumerable - Belongs to System.Collections namespace - Bes tway to write query on collections data types like List, Array etc. - Is return type for LINQ to Object and LINQ to XML queries - Does not support lazy loading. So not recommended apporach for paging kind of scenarios IQueryable - Belongs to System.Linq namesapce - best way to write query data like remote database, serivce collections - Is the return type of LINQ to SQL queries - Supports lazy loading so we can also use in paging kind of scenerios

What is IEnumerable<> in C#?

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.

Why can't you specify the accessibility modifier for methods inside the Interface?

In an interface, we have virtual methods that do not have method definition. All the methods are there to be overridden in the derived class. That's why they all are public.

What is inheritance?

Inheritance is a mechanism in which one object acquires all the properties and behaviour of another object of another class ( the parent class). It represents IS-A relationship. It is used for Code Resusability and Method Overriding.

List the 4 fundamental OOP concepts ?

Inheritance: Polymorphism: Enscapsulation: Abstraction:

Difference between Interface and Abstract Class

Interfaces are contracts that a class must utilize its properties/method. Only allows you to define functionality, NOT implement it. An abstract class is a special type of class that cannot be instantiated. An abstract class is designed to be inherited by subclasses that either implement or override its methods. You can have functionality in your abstract class—the methods in an abstract class can be both abstract and concrete. An abstract class can have constructors—this is one major difference between an abstract class and an interface. You can take advantage of abstract classes to design components and specify some level of common functionality that must be implemented by derived classes. You should use an interface if you want a contract on some behavior or functionality. You should not use an interface if you need to write the same code for the interface methods. In this case, you should use an abstract class, define the method once, and reuse it as needed. Do use interfaces to decouple your application's code from specific implementations of it, or to restrict access to members of a certain type. Whereas an abstract class may contain method definitions, fields, and constructors, an interface may only have declarations of events, methods, and properties. Methods declared in an interface must be implemented by the classes that implement the interface. Note that a class can implement more than one interface but extend only one class. The class that implements the interface should implement all its members. Like an abstract class, an interface cannot be instantiated.

What is absraction?

Is showing only relevent and esstential data without revealing details of the implementation to the user. This helps simplify complex model by focusing on the problem at hand

What is an IEnumerable?

Is the parent interface for all non-generic collections in System.Collections namespace like ArrayList, HastTable, etc. that can be enumerated. The generic version of this interface is IEnumerable<T>, which a parent interface of all generic collections class in System.Collections.Generic namespace, like List<> and more. The recommended way to return a sequence of data because the results are more flexible for the callers of the method.

What is polymorphism?

It is a property of an object which allows it to take multiple forms. Where one task can be performed in several different ways

What is LINQ in C#?

LINQ stands for Language Integrated Query. LINQ is a data querying methodology that provides querying capabilities to .NET languages with a syntax similar to a SQL query. LINQ has a great power of querying on any source of data. The data source could be collections of objects, database or XML files. We can easily retrieve data from any object that implements the IEnumerable<T> interface. Advantages of LINQ LINQ offers an object-based, language-integrated way to query over data no matter where that data came from. So through LINQ, we can query a database and XML as well as collections. Compile-time syntax checking

What is Serialization in C#?

Serialization in C# is the process of converting an object into a stream of bytes to store the object to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization. Json, binary, soap, xml

What is Managed and Unmanaged code?

Managed code is a code which is executed by CLR (Common Language Runtime) i.e all application code based on .Net Platform. It is considered as managed because of the .Net framework which internally uses the garbage collector to clear up the unused memory. Unmanaged code is any code that is executed by application runtime of any other framework apart from .Net. 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

Can multiple catch blocks execute in C#?

No, There can be multiple catch blocks, but only the one that first matches the exception type is executed. That means you need to order the catch blocks properly

What is an object in C#?

Objects are an instances of a class. Objects are created using the class instance with the keyword new. A class has a fields, propperties, method and other members.

What is the difference between overloading and overriding?

Overloading is when you have multiple methods in the same scope, with the same name but different signatures. When youcompile, the compiler makes use of overload resolution to determine the specific method which will be invoked. Under Method overriding the definition (method) of the derived class is changed which in turn changes the method behavior.

What is the difference between late binding and early binding 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 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. 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

List down the differences between Public, Static and void keywords?

Public It is an access specifier which states that the method of a class can be accessed publicly Static It is a keyword used for declaring a member of a type, specific to that type void It states that the method does not return any value

List down the access modifiers available in C#.

Public- When an attribute or method is defined as public it can be accessed from any part of code. Private- A private attribute or method can be accessed from within the class itself. Protected- When a user defines a method or attribute as protected then it can be accessed only within that class and the one inheriting the class. Internal- When an attribute or method is defined as internal then it will be accessed from that class at the current assembly position. Protected Internal- When you define an attribute or method as protected internal, then it's access restricted to classes within the current project assembly or different types defined by that class.

Explain StreamReader/StreamWriter class?

Streamreader and StreamWriter are classes of namespace.System.IO. Used when we want to read or write charact90, Reader based data,respectively. members of StreamReader are: close(), Read(), Readline(). members of Streamwriter are: close(), write(), writeline().

Difference between a struct and a class?

Struct is a VALUE type. Inherits from the System.Value Type -include the primiative types - used for smaller amounts of data - does not support inheritance -members are public by default Class is a REFERENCE type. Inherits from the Systems.Object type. - used for large amounts of data - classes can be inherited from other class - class can be an abstract type - can create a default constructor - members are private by default

Explain Synchronous and Asynchronous Operations?

Synchronization is a way of creating a thread-safe code where only a single thread will access the code in a given time. A synchronous call waits for completion of method and then continous the program flow. Synchronous programming adversely affects the UI operations that normally happens when user tries to perform time-consuming operations since only one thread is used. In Asynchronous operation, the method call immediately returns allowing the program to perform other operations while the method called completes its share of work in certain circumstances.

What are delegates in C#

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 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.

What are accessors?

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. We have three types of properties: Read/Write, ReadOnly, and WriteOnly. Let's see each one by one.

What are the uses of using in C#

The reason for the using statement is to ensure that the object is disposed (call IDisposable) as soon as it goes out of scope, and it doesn't require explicit code to ensure that this happens.

What are the different approaches of passing parameters to a method?

There are three ways of passing parameters to a method: Value Parameters- Under this method the actual value of an argument is copied to the formal parameter of the function. In, this case the changes made into the formal parameter of the function have no effect on the actual value of the argument. Reference Parameters- This method copies the argument referring to the memory location into the formal parameter. Meaning changes made to the parameter affect the argument. Output Parameters- This method returns more than one value.

Illustrate the process of code compilation in C#?

There exist four steps in the process of code compilation: 1. Compilation of Source code in managed code 2. Clubbing the newly created code into assembly 3. Loading the CLR (Common Language Runtime) 4. Execution of assembly through CLR

Define thread? Explain Multithreading?

Thread is a set of instructions that when executed enables the program to perform concurrent processing. Concurrent processing helps in doing more than one process at a time. By default, C# consists of only thread. Other threads can be created to execute the code in parallel with original thread. Thread follows a life cycle where it starts whenever a thread is created and gets terminated immediately after the execution. The namespace it follows is System.Threading which has to be included to create threads and use its members. C# can also execute more than proceeses/task at a time which is done by handling different processes at different time labeled as "multithreading".Several operations of the same are listed below: Start Sleep Abort Suspend Resume Join

What are the uses of delegates?

Using a callback, programmers were able to configure one function to report back to another function in the application. So the objective of using a callback is to handle button-clicking, menu-selection, and mouse-moving activities. But the problem with this traditional approach is that the callback functions were not type-safe. In the .NET framework, callbacks are still possible using delegates with a more efficient approach. 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

What is the difference between "continue" and "break" statements in C#?

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.

What's the difference between the Array.CopyTo() and Array.Clone()?

Using the Clone() method, a new array object is created containing all elements of the original array. Using the CopyTo() method all the elements of the existing array gets copied into another existing array. Both use a shallow copy method.

Can "this" be used within a static method?

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 parameters of the function. 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

What are dynamic type variables in C#?

You can store any type of value in the dynamic data type variable. Type checking for these types of variables takes place at run-time. Syntax for declaring a dynamic type is − dynamic <variable_name> = value; For example, dynamic d = 20;

Define sealed classes in C#?

You create sealed classes in situations when you want to restrict the class to be inherited. For doing this sealed modifiers are used. If you forcefully specify a sealed class as a base class then a compilation error occurs.

Distinguish between finally and finalize blocks?

finally block is called after the execution of try and catch blocks, It is used for exception handling whether or not the exception has been caught this block of code gets executed. Generally, this block of code has a cleaner code. The finalize method is called just before the garbage collection. Main priorities are to perform clean up operation for unmanaged code, it is automatically invoked when an instance is not subsequently called.

What is the difference between ref and out keywords?

ref tells the compiler that the object is initialized before entering the function, while out tells the compiler that the object will be initialized inside the function. So while ref is two-ways, out is out-only.


Ensembles d'études connexes

EXAm FX Life Policy Provision, Riders and Options 4-24-19

View Set

Chapter 70 (2) - Oncologic or Degenerative Neurologic Disorders

View Set

Mastering Biology: Chapter 14 review

View Set

Davis Edge: High-Risk Neonatal Care

View Set

ARM 56 - Chapter 10: Capital Market Risk Financing Plans

View Set

Surgical Technology - Chapter 5 - Fill in the Blank

View Set

3.2 Aggregate supply and macroeconomic equilibrium

View Set