C#(CSharp) Interview Questions & Answers) - Part 4.

C#(CSharp) Interview Questions & Answers) - Part 4.

Links to previous part of C# Interview Q&A :-

C#(CSharp)Interview Questions & Answers) - Part 1.

C#(CSharp) Interview Questions & Answers) - Part 2.

C#(CSharp) Interview Questions & Answers) - Part 3.

Welcome to 4th(Final) Part of C# Interview Questions & Answers.

Q71. What are the generic equivalent for array list, stack, queues and hashtable?

Below are the listed generic equivalents for each of them:-

  • Array list generic equivalent is List<int>.
  • Stack generic equivalent is Stack<int>.
  • Queue generic equivalent is Queue<int>.
  • Hashtable generic equivalent is Dictionary<int,int>.

Q72. What is the use of IEnumerable, ICollection, Ilist and IDictionary?

The above 4 entities are nothing but interfaces implemented by collections:-

IEnumerable: - All collection classes use this interface and it helps to iterate through all the collection elements.

ICollection: - This interface has the count property and it’s implemented by all collection elements.

IList: -This interface allows random access, insertion and deletion in to the collection.Itsimplemented by array list.

IDictionary: -This interface is implemented by hashtable and dictionary.

No alt text provided for this image

Q.73 Differentiate IEnumerable vs Iqueryable?

The first important point to remember is “Iqueryable” interface inherits from “Ienumerable”, so whatever “Ienumerable” can do, “Iqueryable” can also do.

No alt text provided for this image

There are many differences but let us discuss about the one big difference which makes the biggest difference. “IQueryable” interface is useful when your collection is loaded using LINQ or Entity framework and you want to apply filter on the collection.

Consider the below simple code which uses “IEnumerable” with entity framework. It’s using a “where” filter to get records whose “EmpId” is “2”.

No alt text provided for this image

This where filter is executed on the client side where the “IEnumerable” code is. In other words all the data is fetched from the database and then at the client its scans and gets the record with “EmpId” is “2”.

No alt text provided for this image

But now see the below code we have changed “IEnumerable” to “IQueryable”.

No alt text provided for this image

In this case the filter is applied on the database using the “SQL” query. So the client sends a request and on the server side a select query is fired on the database and only necessary data is returned.

No alt text provided for this image

So the difference between “IQueryable” and “IEnumerable” is about where the filter logic is executed. One executes on the client side and the other executes on the database.

So if you working with only in-memory data collection “IEnumerable” is a good choice but if you want to query data collection which is connected with database “IQueryable” is a better choice as it reduces network traffic and uses the power of SQL language.

Q.74 What is code access security (CAS)?

CAS is the part of .NET security model which determines whether or not a particular code is allowed to run and what kind of resources can the code access.

Q.75 So how does CAS actually work?

It’s a four step process:-

  • First Evidence is gathered about the assembly. In other words from where did this assembly come? , who is the publisher etc.
  • Depending on evidences the assembly is assigned to a code group. In other words what rights does the assembly depending on the evidence gathered.
  • Depending on code group security rights are allocated.
  • Using the security rights the assembly is run with in those rights.
No alt text provided for this image

Q76. Is CAS supported in .NET 4.0?

CAS is deprecated in .NET 4.0 and two major changes are brought in:-

  • Permission granting is no more the work of CAS; it’s now the work of the hosting model. In other words CAS is disabled in .NET 4.0 by default. The host will decide what rights to be given to the .NET assembly.
  • A new security model i.e. Security transparent model is introduced. The security transparent model puts code in to separate compartments/ boxes as per the risk associated. If you know a code can do something wrong you can compartmentalize the code as ‘Security transparent’ and if you have a code which you trust you can box them in to ‘Security critical’.

Q.77 What is sandboxing?

If you have want to execute an untrusted third party DLL, you can create your own ‘appdomain’ and assign permission sets so that your 3rd party DLL runs under a control environment.

Q.78 How can we create a windows service using .NET?

Windows Services are long-running processes that runs at the background. It has the ability to start automatically when the computer boots and also can be manually paused, stopped or even restarted.

Following are the steps to create a service:-

Create a project of type “Windows Service”.

No alt text provided for this image


If you see, the class created it is automatically inheriting from “System.ServiceProcess.ServiceBase”

You can override the following events provided by service and write your custom code. All the three main events can be used that is Start, stop and continue.

No alt text provided for this image

Now to install the service you need to do run the install util exe.

No alt text provided for this image

Q.79 What is serialization and deserialization in .NET?

Serialization is a process where we can convert an object state in to stream of bytes. This stream can then be persisted in a file, database, or sent over a network etc. Deserialization is just vice-versa of serialization where we convert stream of bytes back to the original object.

No alt text provided for this image

Below is a simple code of how to serialize and de-serialize an object.

Let’s first start with serialization.

Step 1:- Create the object and put some values

No alt text provided for this image

Step 2:- Create the file where to save the object.

No alt text provided for this image

Step 3:- Use serialize method to save it to hard disk

No alt text provided for this image

Let’s also see a simple example of de-serialization.

Step 1:- Read the file

No alt text provided for this image

Step 2:- Recreate it back to the original object.

No alt text provided for this image

If you want to save to XML or any other content type use the appropriate formatter.

Q.80 Can you mention some scenarios where we can use serialization?

Below are some scenarios where serialization is needed:-

  • Passing .NET objects across network. For example .NET remoting , web services or WCF services use serialization internally.
  • Copy paste .NET objects on clip board.
  • Saving old state of the object and reverting back when needed. For example when the user hits the cancel button you would like to revert back to the previous state.

Q.81 When should we use binary serialization as compared to XML serialization?

  • Binary is smaller in size, so faster to send across network and also faster to process.
  • XML is more verbose, but easy to understand and human readable. But due to the XML structure its complex to parse and can impact performance.
Note :- Many people answer that XML serialization should be used when you have different platforms and binary serialization should be used when you same platforms. But this answer is actually not right as we have lot of binary serialization methodology like ASN , protbuf which are cross platform and widely accepted. So the important difference is that one is XML which readable by eyes and the binary is not.

Q.82 What is Regular expression?

Regular expression is a pattern matching technique. Most of the data follow patterns, some examples of common data patterns are as shown in the below table :-

No alt text provided for this image

By using regular expression you can represent these data patterns and utilize the same for validations and manipulation of data.

In order to use regular expression we need to create the object of "Regex" class and pass the pattern to Regex. For example the below pattern represent's data pattern of 10 character length which can be any small characters from a to z.

No alt text provided for this image

Once you have specified the pattern as described in the previous step you can then use the "IsMatch" function to check if the data matches with the pattern.

No alt text provided for this image
Note :- In some rare cases we have seen interviewers ask to write down regex patterns. So we would suggest to see the video “Explain Regex ?” provided in the DVD which will help you to write down any regex pattern easily.

Q.83 What is time out support in regex (regular expression)?

This is a new feature of .NET 4.5.Some of the regular expressions are very complex and they can take lot of time to evaluate. For instance below is a simple regular expression.

No alt text provided for this image

If someone inputs a huge number as shown in the below code snippet. It will take more than a minute to resolve the expression leading to lot of load on the application. So we would like to give a time out on the expression. So if the validation takes more than a specific interval we would like the application to give up and move ahead.

No alt text provided for this image

In .NET 4.5 we can now provide the timeout value as parameter on the constructor. For instance in the below code we have provided 2 seconds timeout on the regex (regular expression). So if it exceeds more than 2 second “regexMatchTimeOutException” will occur.

No alt text provided for this image

Q.84 Can you explain the concept of “Short Circuiting”?

Short circuiting occurs when you do logical operations like ‘AND’ and ‘OR’.

“When we use short circuit operators only necessary evaluation is done rather than full evaluation.”

Let us try to understand the above sentence with a proper example. Consider a simple “AND” condition code as shown below. Please note we have only one “&” operator in the below code.

No alt text provided for this image

In the above case “Condition2” will be evaluated even if “Condition1” is “false”. Now if you think logically, it does not make sense to evaluate “Condition 2”, if “Condition 1” is false .It’s a AND condition right? , so if the first condition is false it means the complete AND condition is false and it makes no sense to evaluate “Condition2”.

There’s where we can use short circuit operator “&&”. For the below code “Condition 2” will be evaluated only when “Condition 1” is true.

No alt text provided for this image

The same applies for “OR” operation. For the below code (please note its only single pipe (“|”).) “Condition2” will be evaluated even if “Condition1” is “true”. If you think logically we do not need to evaluate “Condition2” if “Condition1” is “true”.

No alt text provided for this image

So if we change the same to double pipe (“||”) i.e. implement short circuit operators as shown in the below code, “Condition2” will be evaluated only if “Condition1” is “false”.

No alt text provided for this image

Q.85 What is the difference between “Typeof” and “GetType” ?

Both “TypeOf” and “GetType” help you to get the type. The difference is from where the information is extracted. “TypeOf” gets the type from a class while “GetType” gets type from an object.

Q.86 Will the following c# code compile?

No alt text provided for this image

No, the above code will give an error. Double size is larger than “int” so an implicit conversion will not take place. For that we need to do explicit conversion. So we need to something as shown in the below code. In the below code we have done an explicit conversion.

No alt text provided for this image

Also note after explicit conversion we will have data loss. In variable “i” we will get “109” value , the decimal values will be eliminated.

Q.87 Explain the use of Icomparable in c#?

“IComparable” interface helps to implement custom sorting for collections in c#. Let us try to understand the same with a simple c# example. For instance let’s say you have a list collection of people names as shown in the below code.

No alt text provided for this image

Now if you run the above program you will see that we have not applied sort on the collection. It displays data as they were inserted.

No alt text provided for this image

But now if you call “Peoples.Sort()” method on the collection you will get the following sorted output on the “name” value in ascending position.

No alt text provided for this image

But now let’s say that we need the person’s age also to be added in the list with the person name value. So logically you will create a “Person” class with “name” and “age” property as shown in the code below.

No alt text provided for this image

Once you create the class you would create an object of the person class and add it to the list collection as shown in the below code snippet.

No alt text provided for this image

But if you now try to call the “Sort” method on the List, he gets confused ?. On which value should he sort on “Name” or “Age” ?.

No alt text provided for this image

If you run the application it will throw up the below exception text. The exception text says that he is confused and he needs specific direction on how the sorting should work. This direction can be provided by using “IComparable” interface.

Unhandled Exception: System.InvalidOperationException: Failed to compare two elements in the array. ---> System.ArgumentException: At least one object must implement IComparable.

So in order to show a proper direction for the sort logic we need to implement “IComparable” interface as shown in the below. The logic of “Sort” needs to be defined in the “CompareTo” method.

No alt text provided for this image

You can see in the “CompareTo” method we have defined the logic saying if the “age” value is same then sort by using the “name” value or else use “age” value for sorting. If you run the application you would get the following output. You can see for “40” and “30” value he has sorted on the basis “Age” but for the remaining people the age is same so he sorted on the “Name” value.

No alt text provided for this image

So the use of “IComparable” interface is to define custom sorting logic on a collection.

Q.88 What is difference between Icomparable and IComparer?

Pre-requisite:- Please read “Explain the use of Icomparable in c#?” , before reading this answer.

“IComparable” interface helps you to implement a default sort implementation for the collection. But what if we want to sort using multiple criteria’s?.For those instances “IComparable” has a limitation and “IComparer” is the guy.

For example if we want to sort the list by “Name” under some situation or sort by “Age” under some other situations we need to implement “IComparer” interface.

So the first step is to create different classes for each sort criteria. These classes will implement “IComparer” interface and will have sorting logic defined in the “Compare” method. You can see we have two different classes defined “CompareByName” and “CompareByAge”. One compares on the basis of “name” and the other on the basis of “age”.

No alt text provided for this image

If you see the logic for “CompareByName” its simple. It uses the string comparison to evaluate the “Name” value sorting. But when we talk about numeric comparison there are 3 possible outputs Greater than , less than or Equal. So if you see “CompareByAge” class it returns 3 values 1 ( Greater than) , -1 ( Less than ) and 0 ( for Equal to).

Now that we have created the separate logics we can now invoke the “Peoples’ list by passing the class object. So for example if we want to sort by name, you will use the below code snippet.

No alt text provided for this image

The output of the above code is nothing but alphabetically sorted data.

No alt text provided for this image

If you invoke the sort method of the list by using the age logic it will throw an output sorted on age value.

No alt text provided for this image
No alt text provided for this image

So the difference is really default internal implementation or customizable external implementation. When we use “IComparable” we can have only one default sorting logic and that logic goes inside the collection itself. For “IComparator” the logic is outside the collection , in other words more extensible and the collection is not disturbed.

No alt text provided for this image

Q.89 Can you explain Lazy Loading?

Lazy loading is a concept where we delay the loading of the object unit the point where we need it. Putting in simple words on demand object loading rather than loading the objects unnecessarily.

For example consider the below example where we have a simple “Customer” class and this “Customer” class has many “Order” objects inside it. Have a close look at the constructor of the “Customer” class. When the “Customer” object is created it also loads the “Order” object at that moment. So even if we need or do not need the address object , it’s still loaded.

But how about just loading the “Customer” object initially and then on demand basis load the “Order” object.

No alt text provided for this image

So let’s consider you have client code which consumes the “Customer” class as shown below. So when the “Customer” object is created no “Order” objects should be loaded at that moment. But as soon as the “foreach” loop runs you would like to load the “Order” object at that point ( on demand object loading).

No alt text provided for this image

Q.90 So how do we implement “LazyLoading” ?

So for the above example if we want to implement Lazy loading we will need to make the following changes:-

  • Remove the “Order” object loading from the constructor.
  • In the “Order” get property, load the “Order” object only if it’s not loaded.
No alt text provided for this image

Now if you run the client code and halt your debugger just before the “ForEach” loop runs over the “Orders”object, you can see the “Orders” object is null ( i.e. not loaded). But as soon as the “ForEach” loop runs over the “Order” object it creates the “Order” object collection.

No alt text provided for this image

Q.91 Are there any readymade objects in .NET by which we can implement Lazy loading?

In .NET we have “Lazy<T>” class which provides automatic support for lazy loading. So let’s say if you want to implement “Lazy<>” in the above code we need to implement two steps for the same:-

Create the object of orders using the “Lazy” generic class.

No alt text provided for this image

Attach this Lazy<> object with the method which will help us load the order’s data.

No alt text provided for this image

Now as soon as any client makes a call to the “_Orders” object ,it will call the “LoadOrders” function to load the data.

You will get the “List<Orders>” data in the “Value” property.

No alt text provided for this image

Below goes the full code for the same.

No alt text provided for this image

Q.92 What are the advantages / disadvantages of lazy loading?

Below are the advantages of lazy loading:-

  • Minimizes start up time of the application.
  • Application consumes less memory because of on-demand loading.
  • Unnecessary database SQL execution is avoided.

The disadvantage is that the code becomes complicated. As we need to do checks if the loading is needed or not. So must be there is a slight decrease in performance.

But the advantages of are far more than the disadvantages.

FYI :- The opposite of Lazy loading is Eager loading. So in eager loading we load the all the objects in memory as soon as the object is created.

Q.93 What is the difference between “IS” and “AS” keyword ?

“IS” keyword is useful to check if objects are compatible with a type. For instance in the below code we are checking if “ocust” object is a type of “Customer” class.

No alt text provided for this image

“AS” keyword helps to do conversion from one type to other type. For instance in the below code we are converting object to a string data type. If the “AS” keyword is not able to type cast it returns NULL.

No alt text provided for this image

Q.94 What is the use of “Yield” keyword?

“Yield helps you to provide custom stateful iteration over .NET collections.”

There are two scenarios where “yield” keyword is useful:-

  • Customized iteration through a collection without creating a temporary collection.
  • Stateful iteration.

Scenario 1:- Customized iteration through a collection

Let’s try to understand what customized iteration means with an example. Consider the below code.

Let say we have a simple list called as “MyList” which has collection of 5 continuous numeric values 1,2,3,4 and 5. This list is browsed/iterated from console application from within static void main method.

For now let’s visualize the “main()” method as a caller. So the caller i.e. “main()” method calls the list and displays the items inside it. Simple…till now ;-).

No alt text provided for this image
No alt text provided for this image

Now let me complicate this situation lets say the caller only wants values greater than “3” from the collection. So the obvious thing as a c# developer we will do is create a function as shown below. This function will have temporary collection. In this temporary collection we will first add values which are greater than “3” and return the same to the caller. The caller can then iterate through this collection.

No alt text provided for this image
No alt text provided for this image

Now the above approach is fine but it would be great if we would get rid of the collection, so that our code becomes simple. This where “yield” keyword comes to help. Below is a simple code how we have used yield.

No alt text provided for this image

So for the above code following are details steps how the control will flow between caller and collection. You can also see the pictorial representation in the next diagram shown below.

  • Step 1:- Caller calls the function to iterate for number’s greater than 3.
  • Step 2:- Inside the function the for loop runs from 1 to 2 , from 2 to 3 until it encounters value greater than “3” i.e. “4”. As soon as the condition of value greater than 3 is met the “yield” keyword sends this data back to the caller.
  • Step 3:- Caller displays the value on the console and re-enters the function for more data. This time when it reenters, it does not start from first. It remembers the state and starts from “5”. The iteration continues further as usual.
No alt text provided for this image

Scenario 2:- Stateful iteration

Now let us add more complications to the above scenario. Let’s say we want to display running total of the above collection. What do I mean?.

In other words we will browse from 1 to 5 and as we browse we would keep adding the total in variable. So we start with “1” the running total is “1”, we move to value “2” the running total is previous value “1” plus current value “2” i.e. “3” and so on.

Below is the pictorial representation of the running total looks like.

No alt text provided for this image

In other words we would like to iterate through the collection and as we iterate would like to maintain running total state and return the value to the caller ( i.e. console application). So the function now becomes something as shown below. The “runningtotal” variable will have the old value every time the caller re-enters the function.

No alt text provided for this image

Below goes the caller code and output.

No alt text provided for this image
No alt text provided for this image

Q.95 What is the difference between “==” and .Equals()?

When we create any object there are two parts to the object one is the content and the other is reference to that content.

So for example if you create an object as shown in below code:-

  1. “.    .NET interview questions” is the content.
  2. “o” is the reference to that content.
No alt text provided for this image
No alt text provided for this image

“==” compares if the object references are same while “.Equals()” compares if the contents are same.

So if you run the below code both “==” and “.Equals()” returns true because content as well as references are same.

No alt text provided for this image
No alt text provided for this image
No alt text provided for this image

Now consider the below code where we have same content but they point towards different instances. So if you run the below code both “==”  will return false and “.Equals()” will return true.

No alt text provided for this image
No alt text provided for this image
No alt text provided for this image

When you are using string data type it always does content comparison. In other words you either use “.Equals()” or “==” it always do content comparison.

Q.96 What’s the difference between catch with parameter and catch without parameter?

First let’s try to understand this question: -

No alt text provided for this image

VS

No alt text provided for this image

For this interview question many people answer, “Second one will cause compile error”. But both the codes will work properly. Actually from .NET 2.0 there is no difference. But in the initial versions of .NET i.e. prior 2.0 some of the exceptions thrown by some COM components did not translate to “Exception” compatible object.

From .NET 2.0 both code will execute properly and there is no difference between them internally. Both catches will handle all kind of exceptions.

After 2.0 a catch which does have any code written in it gives a warning as shown below. So many developers mark this as a difference.

No alt text provided for this image

But you can always overcome this issue by not putting a variable as shown in the below code.

No alt text provided for this image

Q.97 What are attributes and why do we need it?

“Attribute is nothing but a piece of information”.

This information can be attached to your method, class, namespace, assembly etc. Attributes are part of your code this makes developers life easier as he can see the information right upfront in the code while he is calling the method or accessing the class and take actions accordingly.

For instance below is a simple class where “Method1” is decorated by the “Obsolete” attribute. Attributes are defined by using the “[]“ symbol. So when developers starting coding in this class they are alerted that “Method1” is obsolete and code should be now written in “NewMethod1”.

No alt text provided for this image

In the same way if somebody is trying to create object of “Class1” he gets an alert in the tool tip as shown in the below code snippet that “Method1” is obsolete and he should use “NewMethod1”.

No alt text provided for this image

So in short Attributes are nothing small piece of information which is embedded declaratively in the code itself which developers can see upfront.

In case you want to show some message to the developers you can pass the message in the “Obsolete” attribute as shown in the below code snippet.

No alt text provided for this image

If you want to be bit strict and do not developers to use that method, you can pass ‘true” to the “Obsolete” attribute as shown in the below code.

No alt text provided for this image

If you want to be bit strict and do not developers to use that method, you can pass ‘true” to the “Obsolete” attribute as shown in the below code.

No alt text provided for this image

If you want to be bit strict and do not developers to use that method, you can pass ‘true” to the “Obsolete” attribute as shown in the below code.

No alt text provided for this image

Now in case developers try to make a call to “Method1”  they will get error and not just a simple warning.

No alt text provided for this image

Q.98 How can we create custom Attributes?

The “Obsolete” attribute which we discussed at the top is a readymade attribute To create a custom attributes you need to inherit from the attribute class. Below is a simple “HelpAttribute” which has a “HelpText” property.

No alt text provided for this image

“HelpAttribute” is applied to the “Customer” as shown in the code below. Now developers who see this class , see the information right in the front of their eyes.

No alt text provided for this image

Q.99 How can we mark a method as deprecated?

Refer the previous answer.

What is the difference between Build Vs Rebuild Vs Clean solution menu?

No alt text provided for this image
  • Build solution menu: - This will perform an incremental build. In other words it will only build code files which have changed. If they have not changed those files will not touched.
  • Rebuild solution menu: - This will delete all current compiled files (i.e. exe and dll’s) and will build everything from scratch, irrespective if there is code change in the file or not.
No alt text provided for this image

Clean solution menu: - This menu will delete all compiled files (i.e. EXE’s and DLL’s) from “bin” / “obj” directory.

Now if you read the above 3 points I have discussed you can conclude that:-

No alt text provided for this image

So the next question would be If you do a “Rebuild” and if you do “Clean” + “Build” , what is the difference ?

The difference is the way the build and clean sequence happens for every project. Let’s say if your solution has two projects “proj1” and “proj2”. If you do a rebuild it will take “proj1” , clean ( delete) the compiled files for “proj1” and build it. After that it will take the second project “proj2” , clean compiled files for “proj2” and compile “proj2”.

But if you do a “clean” and build”. It will first delete all compiled files for “proj1” and “proj2” and then it will build “proj1” first followed by “proj2”.

Below image explains the same in a more visual format.

No alt text provided for this image

Q.100 What is the difference between i++ vs ++i ?

i++ :- In this scenario first the value is assigned and then increment happens. In the below code snippet first the value of “i” is assigned to “j” and then “i” is incremented.

No alt text provided for this image

++i :- In this scenario first the increment is done and then value is assigned.In the below code snippet value of “j” is 2 and value of “i” is also 2.

No alt text provided for this image

If you visualize in a pictorial manner below is how it looks like. So i++ is a post fix , it first assigns and then increments. While ++i is a prefix, it first increments and then assigns the value.

No alt text provided for this image

Below are some sample code where postfix and prefix fits in.

No alt text provided for this image
No alt text provided for this image
No alt text provided for this image

Q.101 When should we use “??”(NULL Coalescing operator)?

“??” is a NULL coalescing operator. If you see the English meaning of coalescing it says “consolidate together”.Coalescing operator returns the first NON-NULL value from a chain. For example below is a simple coalescing code which chains four strings.

So if “str1” is null it will try “str2” , if “str2” is null it will try “str3” and so on until it finds a string with a non-null value.

No alt text provided for this image

Q.102 Explain need of NULLABLE types ?

It is difficult to assign NULLdirectly for value types like int , bool , double etc. By using NULLABLE types you can set value types as NULL. To create a NULLABLE type we need to put “?” before the data type as shown in the below code.

No alt text provided for this image

Q. 103 In what scenario’s we will use NULLABLE types ?

The biggest user of NULLABLE types is when you are reading values from database. Database is one place where there is high possibility of column having NULL’s. So when we want to read those values in to value types NULLABLE types makes it easy as shown in the below code.

No alt text provided for this image

Q. 104 What is the benefit of coalescing?

You do not need to write long if condition as shown below.

No alt text provided for this image


Happy Learning & Happy Job Hunting from QuestPond...!!!

Get our 200+ C#, Angular and ASP.NET MVC Questions & Answers course - https://www.questpond.com/customcourse.php

Like
Reply

To view or add a comment, sign in

Others also viewed

Explore topics