C# Questions Part 2

 

32. What is an array? Explain Single and multi-dimensional arrays.

The array stores the value of the same type.

Single-dimensional array stores variables in a single row. 

int[] marks = new int[3] { 25, 34, 89 };

Arrays can have more than one dimension. Multi-dimensional arrays are also called rectangular Arrays.

int[,] numbers = new int[3, 2] { { 1, 2 }, { 2, 3 }, { 3, 4 } };


33. What is the difference between the System.Array.CopyTo() and System.Array.Clone()?

CopyTo(): 

  • All the items are copied to the existing array
  • Required a pre-allocated destination array
  • Overwrites the elements in the destination array starting from the specified index. 
  • It allows you to control where the copying starts in the destination array.
Clone(): 
  • Creates and returns a new array with the same elements as the original array
  • Don't need to pre-allocate the destination array
  • It doesn't overwrite any existing elements.
Both ways create a shallow copy.


34. What is the difference between an array and an arraylist?

  1. When we want to store the items of the same type, then the array is used.
  2. The array has a fixed size but not in the case of an arraylist. 
  3. We can store any type of data type in an array list. It's not type-safe, and need to typecast the elements while accessing it.


35. What is a jagged array in C#?

  • A jagged array is like a nested array
  • Each element of a jagged array is an array in itself
  • The item of a jagged array can be of different dimensions and sizes

36. What is the difference between struct and class?

Class and struct are both user-defined but have a significant difference.

Struct

  • A Struct inherits from System. Value type and so it is a value type.
  • It is preferred to use struct when there is a small amount of data. 
  • A structure cannot be abstract.
  • There is no need to create an object with a new keyword.
  • Struct does not have permission to create any default constructor.

Syntax of struct

Class

  • The class is a reference type in c#, and it inherits from the System. Object Type.
  • When there is a large amount of data, then in that scenario, classes are used.
  • We can inherit one class from another class.
  • A class can be an abstract type.

37. What is the difference between throw and throw ex?

The “Throw” statement holds the original error stack of the previous function or function hierarchy.

In contrast, “Throw ex” has the stack trace from the throw point.

So it is always advised to use “Throw” because it provides exact error information related to the function and gives you actual trace data of the error source.


38. Explain the difference between finally and finalize block?

Finally, it is a code block part of execution handling this code block executes irrespective of whether the exception occurs or not.

While the finalize method is called just before garbage collection. The compiler calls this method automatically when not called explicitly in code.


39. Explain var and dynamic.

  • We can declare the var type of a variable without specifying the .net data types explicitly
  • We cannot declare a var type variable without assigning a value to it
  • The data type of the var type variable cannot be changed later in the code


  • The data type of the dynamic variable can be changed later in in the code 
  • It also decides the type of the variable based on the value assigned to it 

In the above example, if we declare the variable “someValue ” to type var instead of dynamic, it throws an error. Because we changed the datatype.


40. What are Anonymous types in C#?

  • Anonymous types are useful when we need to create a simple, read-only data structure for a specific task without explicitly declaring a class or structure

  • Anonymous types are typically created using the new keyword with an object initializer syntax

  • The compiler automatically generates a class with read-only properties based on the properties you define in the initializer
Note:
Anonymous types are read-only, meaning we can't modify their properties once they are set.

Their scope is limited to the method or block where they are defined.


41. What is multithreading, and what are its different states?

Any code block in c# runs in a process called a thread, and it is the execution path of the program. Usually, an application runs in a single thread. Multithreading helps to run the application in multiple threads. Using multithreading, we can divide the execution of our process among different threads to execute it simultaneously.

In multithreading, we can create multiple threads and assign particular tasks or put a code block to get executed. In this way, we can run more than one task at a time. This code block executes simultaneously and can save time, and in this way, we can make programs more efficient and fast.

Thread has its lifecycle, which includes various states of thread.

Aborted256The thread state includes AbortRequested and the thread is now dead, but its state has not yet changed to Stopped.
AbortRequested128The Abort(Object) method has been invoked on the thread, but the thread has not yet received the pending ThreadAbortException that will attempt to terminate it.
Background4The thread is being executed as a background thread, as opposed to a foreground thread. This state is controlled by setting the IsBackground property.
Running0The thread has been started and not yet stopped.
Stopped16The thread has stopped.
StopRequested1The thread is being requested to stop. This is for internal use only.
Suspended64The thread has been suspended.
SuspendRequested2The thread is being requested to suspend.
Unstarted8The Start() method has not been invoked on the thread.
WaitSleepJoin32The thread is blocked. This could be the result of calling Sleep(Int32) or Join(), of requesting a lock – for example, by calling Enter(Object) or Wait(Object, Int32, Boolean) – or of waiting on a thread synchronization object such as ManualResetEvent.
Source: https://docs.microsoft.com/en-us/dotnet/api/system.threading.threadstate?redirectedfrom=MSDN&view=netcore-3.1

42. How is exception handling done in C#?

Try, catch, finally, and throw. These are the keywords used to handle the exception.

  • Try: We keep the code in the try block for which we want to handle the exception.
  • Catch: When any exception occurs in a try block, then it is caught in a catch block with the help of an exception handler.
  • Finally: To execute a code block irrespective of error, we place that code in the finally block to get executed.
  • Throw: Throws an exception when an issue occurs.

43. What are the custom exceptions?

Sometimes some errors need to be caught as per user requirements. Custom exceptions are used for them and are user-defined exceptions.


44. What is LINQ in C#?

The language-integrated query is the full form of LINQ. It is a method of querying data using the .net capabilities and c# syntax similar to SQL query.

The advantage of LINQ is that we can query different sources of data. The data source could be either a collection of objects, XML files, JSON files, In-memory data or lists or, database objects. We can easily retrieve data from any object that implements the IEnumerable<T> interface.

Below is the syntax of LINQ.


45. What is serialization?

  • When we want to send an object through a network, then we have to convert that object into a stream of bytes, the process is called Serialization.
  • To facilitate the object for serializable, it should implement ISerialize Interface. 
  • The process of De-serialization is the reverse process of creating an object from a stream of bytes. 


46. What are generics in c#?

  • Generics enable us to create classes, interfaces, methods, and delegates that can work with any data type
  • We can create collection classes
  • It is preferred to use System.Collections.Generic namespace
  • Type Safety: Provide compile-time type checking, ensuring that the code is type-safe. This helps catch errors at compile time rather than at runtime
  • Code Reusability: Can write classes and methods that can be reused with different data types
  • Performance: Generics can result in better performance compared to non-generic code in certain situations. This is because the compiler can generate more efficient code for specific data types.

47. What is reflection?

Reflection is when managed code can read its own metadata to find assemblies.

“Reflection provides objects (of type Type) that describe assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. If you are using attributes in your code, reflection enables you to access them. For more information, see Attributes.”

Source: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/reflection

The following information can be retrieved using reflection.

  • Assembly name
  • Class name
  • Method name
  • Object type
  • It Identifies properties and methods.

48. How to use nullable types?

In c#, we can also assign a null value to the variable. Such types are called nullable types.


49. Which is the parent class of all classes that we create in C#?

System.object.


50. Explain code compilation in C#.

Below are the steps explaining the code compilation.

  • The C# compiler compiles the code into managed code, also called Byte code.
  • Then JIT (Just in time compiler) compiles the Byte code into Native or machine language, which is directly executed by the CPU.

51. What is .NET?

Using .NET we can develop any application like console app, windows app, web app, mobile app, windows services, web services, etc.

Collection of libraries and runtimes.
It's a language and OS-neutral platform.

Langauges such as: C#, C++, VB,..
Note: With the .NET core only, OS neutral platform can be accomplished.



52. What is .NET Framework & .NET Core?

.NET Framework
  • Oldest framework
  • Not open source (source code not present in GitHub)
  • Target only on Windows OS
  • Components such as WPF, Windows Forms, WCF, ASP.NET Web API, ASP.NET Web Pages, SignalR, etc.
.NET Core
  • New framework
  • Open source
  • Target on Windows, Linux, Mac OS
  • Doesn't have all the components just have ASP.NET Core and Universal Windows app



53. What is 'this' keyword?

  1. An object of the parent class and used to initialize parent class fields

  2. Used to call one constructor to another.



54. What is constructor chaining or base keyword?

  1. Calling the parent class constructor from the child class constructor using the base keyword is called a constructor chaining
  2. The default constructor or parameterized constructor of a child class always invokes the default constructor of the parent class.


    Both are the same if we add the base keyword.



  3. Also used to refer to the members of the parent class from the child class.



55. What are collection classes?

  1. Use to store the multiple number of elements
  2. Like stack, queue, list, arraylist, dictionary, etc.
  3. Present in System.Collection namespace
Note: In C#, the ArrayList is part of the older collection classes that can store elements of any data type. However, with the introduction of generics in .NET Framework 2.0, newer and more type-safe collection classes were introduced in the System.Collections.Generic namespace.

If you want to store elements of any data type in a type-safe manner, you can use the List<T> class.



56. What are the different types of method calling?

  1. Call by Value,
  2. Call by Reference,
  3. Call by Output,
  4. Call by Params
Params: 
  • Used as a parameter which can take the number of variables arguments
  • No additional Params keyword will be allowed in the function declaration after one Params keyword used
  • The length of Params will be zero if no arguments are passed


57. What are Named Parameters?




58. What is the Null Coalesce operator (??)?
  • Returns the left side operand if the operand is not null, else it returns the right side operand
  • Returns the first non-null value from the chain
string a = null;
string b = "abhishek";
string result = a ?? b; 

Result: abhishek

string a = null;
string b = null;
string c = "singh";
string result = a ?? b ?? c; 

Result: singh



59. What is a concrete class?
  • A class that has an implementation for all of its methods.
  • It can also extend an abstract class or implement an interface as long as it implements all its methods.


60. What is ?

Popular posts from this blog

Introduction to Docker

SOLID Principles

Nuget package | Pushing it to Azure Artifacts

WiX - Windows Installer XML

Working with Git

C# Memory Tricks: Learn How To Master The Garbage Collector

gRPC - Protobuf / Protocol Buffers

Custom Azure DevOps pipeline task extension

C# Questions Part 1