Top C# Interview Questions

1) What is Asynchronous Programming ?

-> Asynchronous programming maximizes utilization of resources on multicore systems, by allowing units of work to be separated and completed.
-> It frees up the calling system, especially a user interface, as to not wait for long operations.
-> Async and await simplify asynchronous programming
-> Async and await allow asynchronous code to resemble the structure of synchronous code.
-> The async keyword instructs the compiler to allow await.
-> Methods marked with async may return Task<T>
-> The await keyword instructs the method to return.
-> The await keyword instructs the complier to resume execution within the same context after the operation is complete.

2) What is Linq ?

-> Language Integrated Query or Linq is the collection of standard query operators which provides query facilities into .Net framework language like C#, Vb.Net.

Types of Linq
-> Linq to Objects
-> Linq to XML
-> Linq to Dataset
-> Linq to SQL
-> Linq to Entities

3) Explain Thread Safety ?

Thread safety is a computer programming concept applicable in the context of multi-threaded programs. A piece of code is thread-safe if it only manipulates shared data structures in a manner that guarantees safe execution by multiple threads at the same time.

->3 main thread synchronization techniques in c#
->lock, mutex, semaphore

Mutex
-> When two or more threads need to access a shared resource at the same time, the system needs a synchronization mechanism to ensure that only one thread at a time uses the resource. Mutex is a synchronization primitive that grants exclusive access to the shared resource to only one thread. If a thread acquires a mutex, the second thread which wants to acquire that mutex is suspended until the first thread releases the mutex.

-> We can use WaitHandle.WaitOne method to request ownership of a mutex.

4) What is a delegate ?

-> A delegate is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke or call the method through the delegate instance.
-> Delegates are used to pass methods as arguments to other methods. Event handlers are nothing more than methods that are invoked through delegates.
-> Delegates can be used to define callback methods.
-> Delegates can be chained together; multiple methods can be called on a single event.

There are three types of delegates that can be used in C#.

  • Single Delegate
  • Multicast Delegate
  • Generic Delegate

Single Delegate
-> Single delegate can be used to invoke a single method.

Multicast Delegate
-> can be used to invoke multiple methods. The delegate instance can do multicasting (adding new method on existing delegate instance) using + operator and – operator can be used to remove a method from a delegate instance. All methods will invoke in sequence as they are assigned.

Generic Delegate
-> don’t require to define the delegate instance in order to invoke the methods. There are three types of generic delegates.
-> was introduced in .Net 3.5

1) Func
2) Action
3) Predicate

Action Delegate Type
-> The generic Action delegate represents a method that returns void. Different versions of Action take between 0 and 18 input parameters.
-> The action delegate that takes two arguments.

Func Delegate Type
-> Func in short is parameterized delegate.
-> The generic Func delegate represents a method that returns a value.
-> Func handles many arguments.
-> It provides a way to store anonymous methods in a generalized and simple way.

5) Explain finalize and dispose ?

-> They are used to clean up unmanaged resources.
-> Class instances often encapsulate control over resources that are not managed by the run time, such as windows handles (HWND), database connections and so on. Therefore we should provide both an explicit and implicit way to free those resources.
-> We can provide implicit control by implementing the protected Finalize on an object (destructor). The garbage collector calls this method at some point after there are no longer any valid references to the object.
-> In some cases, we might want to provide programmers using an object with the ability to explicitly release these external resources before the garbage collector frees the object. If and external resource is scarce or expensive, better performance can be achieved if the programmer explicitly releases resources when they are no longer being used. To provide explicit control, implement the Dispose provided by IDisposable. The consumer of the object should call this method when it is finished using the object. Dispose can be called even if other references to the object are alive.
-> Even when you provide explicit control using Dispose, you should provide implicit clean up using the Finalize method. Finalize provides a back up to prevent resources from permanently leaking if the programmer fails to call Dispose.

Dispose Finalize
It is used to free unmanaged resources like files, database connections etc. at any time. It can be used to free unmanaged resources (when you implement it) like files, database connections etc. held by an object before that object is destroyed.
Explicitly, it is called by user code and the class which is implementing dispose method, must has to implement IDisposable interface. Internally, it is called by Garbage Collector and cannot be called by user code.
It belongs to IDisposable interface. It belongs to Object class.
It’s implemented by implementing IDisposable interface Dispose() method. It’s implemented with the help of destructor in C++ & C#.
There is no performance costs associated with Dispose method. There is performance costs associated with Finalize method since it doesn’t clean the memory immediately and called by GC automatically.

6) Difference between Boxing and Unboxing ?

-> Boxing is the process of converting a value type to the type object or to any type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. Unboxing extracts the value type from the object.

-> Boxing is used to store value types in the garbage-collected heap. Boxing is an implicit conversion of a value type to the object or to any interface type implemented by this value type.

-> An unboxing operation consists of :
1) Checking the object instance to make sure that it is a boxed value of the given value type.
2) Copying the value from the instance in to the value-type variable.

7) What is Reflection ?

-> is the ability of a managed code to read its own metadata for the purpose of finding assemblies, modules and type information at runtime.
-> Reflection inspects type metadata at run time.
-> The type metadata contains information such as
– The type name
– The containing assembly
– Constructors
– Properties
– Methods
– Attributes
-> This data can be used to create instances, access values and execute methods dynamically at runtime.
-> There are two ways to dynamically instantiate a type.
– Activator.CreateInstance
– Calling Invoke on a ConstructorInfo object (advanced scenarios)

8) What is the use of using block ?

-> is used to obtain a resource and use it and then immediately dispose of when execution of block is completed.
-> The using statement is combined with a type that implements IDisposible.

9) What is the difference between Encryption and Hashing ?

Encryption
-> Encryption is the process of transforming plain data in a way that makes it harder for an unauthorized person to make sense of it. The encrypted data is called ciphertext.
-> An encryption algorithm makes data unreadable to any person or system until the associated decryption algorithm is applied.
– Encryption does not hide data; it makes it unreadable
– Encryption is not the same as compression
1) Computers agree on how to encrypt.
Key – RSA, Diffie-Hellman, DSA
Cipher – RC4, Triple DES, AES
Hash – MD5, SHA
2) Server sends certificate
3)Your computer says ‘start encrypting’
4)The server says ‘start encrypting’
5)All messages are now encrypted.

Types of Encryption

  • File Encryption
  • Windows Data Protection
  • Hashing, used for signing and validating
  • Symmetric and Asymmetric

Symmetric Encryption
-> One key is used for both encryption and decryption.
-> faster than asymmetric encryption
-> Cryptography namespace includes five symmetric algorithms
– Aes, DES, RC2, Rijndael, TripleDES
DES -> Data Encryption Standard
AES ->Advanced Encryption Standard

Asymmetric (or Public Key) Encryption
-> One key is used for encryption and other is another key for decryption
-> Cryptography namespace includes four symmetric algorithms
– DSA, ECDDiffieHellman, ECDsa, RSA

Hashing
-> Hashing is the process of mapping binary data of a variable length to a fixed size binary data.
-> One-way encryption
-> Common algorithms:
– MD5 (generates a 16 character hash that can be stored in a GUID)
– SHA (SHA1, SHA256, SHA384, SHA512)
-> Used of storing passwords, comparing files, data corruption/tamper checking
– Use SHA256 or greater for storing password.

10) Difference between Single , SingleOrDefault, First, FirstOrDefault ?

 Single()SingleOrDefault()First()FirstOrDefault()
DescriptionReturns a single, specific element of a sequenceReturns a single, specific element of a sequence, or a default value if that element is not foundReturns the first element of a sequenceReturns the first element of a sequence, or a default value if no element is found
Exception thrown whenThere are 0 or more than 1 elements in the resultThere is more than one element in the resultThere are no elements in the resultOnly if the source is null (they all do this)
When to useIf exactly 1 element is expected; not 0 or more than 1When 0 or 1 elements are expectedWhen more than 1 element is expected and you want only the firstWhen more than 1 element is expected and you want only the first. Also it is ok for the result to be empty

11) What are extension methods in C# ?
-> Extension methods enables us 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 there were instance method on the extended type.
-> An extension method is a static method of a static class, where the ‘this’ modifier is applied to 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.
Benefits
-> Extension methods allow existing classes to be extended without relying on inheritance or having to change the class’s source code.
-> If the class is sealed then we can’t inherit or extend its functionality. For this a new concept is introduced, in other words extension methods.

 

12) What is the use of volatile keyword in C# ?
->The volatile keyword indicates that a field might be modified by multiple threads that are executing at the same time.
-> Fields that are declared volatile are not subject to compiler optimizations that assume access by a single thread.

13) What are the differences between const and readonly ?
-> A const can not be static, while readonly can be static.
-> A const need to be declared and initialized at declaration only, while readonly  can be initialized at declaration or by the code in the constructor.

14) What are the multiple techniques provided for leveraging threads ?
-> Manual/Explicit
-> Thread pool
-> Asynchronous I/O

Leave a Reply

Your email address will not be published. Required fields are marked *