C# Interview Questions and Answers (958) - Page 25

What is Big Integer Class?What problem it addresses?

BigInteger class resides in the System.Numerics namespace.It helps in representing any large integer without any loss of precision. It has been introduced earlier in dotnet framework 3.5 but was removed. However, it is again back in framework 4.0.

Example: To find the factorial of 100.

static void Main(string[] args)

{
Console.Write("Factorial of hundred is : ");
HundredFactorial();
Console.Read();
}
private static void HundredFactorial()
{
BigInteger number = 100;
BigInteger fact = 1;
for (; number-- > 0; ) fact *= number+1;
Console.WriteLine(fact);
}


Output

Factorial of hundred is :  93326215443944152681699238856266700490715968264381621

46859296389521759999322991560894146397615651828625369792082722375825118521091686
4000000000000000000000000


It exposes some methods as

a) GreatestCommonDivisor [ BigInteger.GreatestCommonDivisor(12, 24) ]
b) Compare [ BigInteger.Compare(num1, num2) ]
c) Parse [ BigInteger.Parse("10000000") ]
d) Negate [ BigInteger.Negate(100) ]
etc.
What is the benefit if we write if( 1 == myobject) { //some code } as opposed to if( myobject == 1 ){ //some code } ?

The
if (1 == myobject)  { //some code }
is a safe way of writing an if statement. It comes from C/C++ where the condition is an expression evaluated to an int.
If the result is zero that means false, anything else is true.
We can write something like
if (myobject == 1){ //some code }

but if we weren’t careful we could also write
if (myobject = 1) { //some code }

in which case we have an assignment that always evaluates to 1 and thus is always true.This will compile and run with no problems, but the result wouldn’t be as expected. So C/C++ programmers started to write things like
if (1 == myobject)  { //some code }

This won’t compile if we misspell it, so we always had to write it as we meant to write it. Later on this became a good practice and we use it in all the languages - C# for example.
What is Co-Variance and Contra Variance in C#4.0? Explain with example

Converting from a broader type to a specific type is called co-variance.If B is derived from A and B relates to A, then we can assign A to B. Like A=B. This is Covariance.

Converting from a more specific type to a broader type is called contra-variance. If B is derived from A and B relates to A, then we can assign B to A. Like B= A. This is Contravariance.

Co-variance and contra-variance is possible only with reference types; value types are invariant.

Co-variance is guaranteed to work without any loss of information during conversion. So, most languages also provide facility for implicit conversion. Contra-variance on the other hand is not guaranteed to work without loss of data. As such an explicit cast is required. Though, both are type-safe and will compile perfectly and run. e.g. Assuming dog and cat inherits from animal, when you convert from animal type to dog or cat, it is called co-variance. Converting from cat or dog to animal is called contra-variance, because not all features (properties/methods) of cat or dog is present in animal.

In .NET 4.0, the support for co-variance and contra-variance has been extended to generic types. No now you can apply co-variance and contra-variance to Lists etc. (e.g. IEnumerable etc.) that implement a common interface. This was not possible with .NET versions 3.5 and earlier.

class Fruit { }


class Mango : Fruit { }

class Program
{
delegate T Func<out T>();
delegate void Action<in T>(T a);

static void Main(string[] args)

{
// Covariance
Func<Mango> mango = () => new Mango();
Func<Fruit> fruit = mango;
// Contravariance
Action<Fruit> fr = (frt) =>
{ Console.WriteLine(frt); };
Action<Mango> man = fr;
}
}

What is the difference between Closing a database connection and Disposing a database connection?And why we must Dispose an external resource like database connection?

We can reopen it later if we close a database connection. But if we Dispose a database connection we cannot use it anymore.We must create a new database object.

We must invoke Dispose method or Using statement whenever we have to free external resources. Else we may encounter the below error

An exception of type 'System.InvalidOperationException' occurred in System.Data.dll but was not handled in user code Additional information: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.
How will you make a combination of the Enum values in C# ? Explain with an example.

In C#, we have to decorate the Enum with Flag attribute and use a bitwise operator to make a combination of the values.

Let us look at the below example

class Program

{
static void Main(string[] args)
{
Console.WriteLine(Fruits.AllFruits.HasFlag(Fruits.Guava));
Console.ReadKey();

}

[Flags]
enum Fruits
{
Apple = 1,
Mango = 2,
Banana = 3,
Guava = 4,
AllFruits = Apple | Mango | Banana | Guava,
AppleANDGuava = Apple & Guava
}

}

/* Result */
True


We are checking if the Guava is present in the "AllFruits" enum.
What is "using " keyword doing in "using SQL = System.Data.SqlServer"?

It's an alias.The user can use SQL to refer to System.Data.SqlServer.
e.g.
using SQL = System.Data.SqlServer;

SQL.SqlConnection sql = new SQL.SqlConnection();


It's useful if we don't want to use the whole namespace (in case of name clash issues for example).
How will you check the Public visibility of a property?

By using the GetSetMethod method of the PropertyInfo .The method will return null if the getter/setter is non-public.

bool isPublicProperty = propertyInfo.GetSetMethod() != null;

How will you use Take and Skip extension method to judiciously do batch operation?

Say we have a bulk of records(take 40 for example sake). Now let us do a batch operation for 10 records each time. The program will be

var intList = new List<int>();

Enumerable.Range(1, 40).ToList().ForEach(i => intList.Add(i));

int setRecordCount = 10;

//Pick the records from 1 - 10
var record1To10 = intList.Skip(setRecordCount * 0).Take(setRecordCount);

//Pick the records from 11 - 20
var record11To20 = intList.Skip(setRecordCount * 1).Take(setRecordCount);

//Pick the records from 21 - 30
var record21To30 = intList.Skip(setRecordCount * 2).Take(setRecordCount);

//Pick the records from 31 - 40
var record31To40 = intList.Skip(setRecordCount * 3).Take(setRecordCount);


In the first case, we are skipping no records and picking up the first 10 records from the original 40 records. In the second case, we are first skipping the 10 record
from the entire 40 records. So from the remaining 30 records(i.e. 11 to 40), we are picking up the first 10 records i.e. 11 to 20.

A similar explanation follows for the rest of the two cases also.
What is Anonymous functions ?

An anonymous function is an "inline" statement or expression that can be used wherever a delegate type is expected. We can use it to initialize a named delegate or pass it instead of a named delegate type as a method parameter
e.g.

In C# 2.0:

var output = doSomething(variable, delegate {

// Anonymous function code
});


In C#4.0:

var output = doSomething(variable, () => {

// Anonymous function code
});

Different types of Threading..

The Threading are of 5 types.They are
1) Running
2) Wait/Sleep/Join
3) Abort
4) Resume
5) Suspend

Explanation:

If you start a thread by Thread.Start, then the thread will moves to the running state.
The Thread in the Running state can move to 3 different states.
You can directly move from running state to abort state,by calling Abort method and then finally moving to sleep state.
If you want to suspend the thread,then you can call the suspend method and let the thread move to the suspend state and then move to running state by calling Resume method.
A thread can go to Wait/Sleep/Join in 3 ways.
When the Monitors Wait method is called,then it is the first way.Thread will again go back to Running state when the Pulse method of the Monitor object is called.
The second way is by calling the Sleep method,the thread can go in Wait/Sleep/Join state.
After the specified millisecond elapses the thread comes back to Running state.
The third way is calling the join method. When the join method is called the thread goes in the Wait/Sleep/Join state. Once the other thread finishes this dependent thread is released either to Running or Aborted depending on what kind of logic it is currently running.
How to get the total number of elements in an array ?

By using Length property, we can find the total number of elements in an array.
Below is an example which explains clearly.

Example:

using System;
namespace ConsoleApplication
{
class Program
{
static void Main()
{
int[] Numbers = { 2, 5, 3, 1, 4 };
Console.WriteLine("Total number of elements = " +Numbers.Length);
}
}
}

How to copy one array into another array ?

We can copy one array into another array by using copy To() method.

Example:

using System;
namespace ConsoleApplication
{
class Program
{
static void Main()
{
int[] Numbers = { 2, 5, 3, 1, 4 };
int[] CopyOfNumbers=new int[5];
Numbers.CopyTo(CopyOfNumbers,0);
foreach (int i in CopyOfNumbers)
{
Console.WriteLine(i);
}
}
}
}

How can we invoke a method being defined inside a Base Class (Abstract class) without the Derived class being inheriting it?

We can do so if we declare the method as static. Then by using Classname.MethodName() we can invoke it.

Example:

class Program

{
static void Main(string[] args)
{
MyBase.Hello();

Console.ReadKey();
}

}

public abstract class MyBase
{
public static void Hello()
{
Console.WriteLine("Hello");
}
}

Write a linq query to find the N-th highest salary of employee. Also the query shoudl be able to handle the Tie situation i.e. the program has to return a collection when multiple employees have equal salary.

Let us first make the environment.First let us declare an Employee class

class Employee

{
public string EmpName { get; set; }
public int Salary { get; set; }
}


Then populate some records to it

private static List<Employee> GetEmpRecord()

{
List<Employee> empCollection = new List<Employee>();
empCollection.Add(new Employee { EmpName = "Emp1", Salary = 10000 });
empCollection.Add(new Employee { EmpName = "Emp2", Salary = 3456 });
empCollection.Add(new Employee { EmpName = "Emp3", Salary = 14256 });
empCollection.Add(new Employee { EmpName = "Emp4", Salary = 15000 });
empCollection.Add(new Employee { EmpName = "Emp5", Salary = 10000 });
empCollection.Add(new Employee { EmpName = "Emp6", Salary = 6000 });
empCollection.Add(new Employee { EmpName = "Emp7", Salary = 2000 });
empCollection.Add(new Employee { EmpName = "Emp8", Salary = 5000 });
empCollection.Add(new Employee { EmpName = "Emp9", Salary = 7000 });
empCollection.Add(new Employee { EmpName = "Emp10", Salary = 7000 });
return empCollection;
}

Finally let us write the program

var empCollection = GetEmpRecord();

int whichEmpSalary = 3;

var employees = (from emp in empCollection
group emp by emp.Salary into g
orderby g.Key descending
select new
{
EmpRecord = g.ToList()
}).ToList();

employees[whichEmpSalary - 1].EmpRecord
.ForEach(i => Console.WriteLine("Emp Name {0} earns {1}", i.EmpName, i.Salary));

Console.ReadKey();


Let us analyze the program. First we are grouping up the Employee Record Set by their salary.If we put a break point there and check , we will find that there are a total of 8 elements since both Emp1 and Emp5 are earning 10000 while Emp9 and Emp10 are earning 7000 each.But it is not sorted. In order to sort the record set, we have introduce the order by clause that will guaranteed to bring the result in a sorted order.Finally we are projecting the record using the select statement.At this stage we will get the count as 8 only but with sorted record set.Suppose we want to find out the third highest salary which should be "Emp1" and "Emp5" (both earning 10000 each). The first will be "Emp4" with 15000 and second is "Emp3" with Salary = 14256.Since it is a collection, we can use index as shown under to obtain the desired result.
var result = employees[2];

will give the desire result.
Output
Emp Name Emp1 earns 10000

Emp Name Emp5 earns 10000


//Lambda version
empCollection

.GroupBy(g=>g.Salary)
.OrderByDescending(o=>o.Key)
.Select(s=>new{EmpRecord = s.ToList()})
.ToList()[whichEmpSalary - 1].EmpRecord
.ForEach(i => Console.WriteLine("Emp Name {0} earns {1}", i.EmpName, i.Salary));

What is diamond of death in OOPS?

Its an ambiguity arises when two class inherits the same base class and one more class inherits these two classes. If class Derived A and class Derived B inherits class BaseClass where BaseMethod() is a method and class Derived C inherits class Derived A and class Derived B and override the method BaseMethod() , then there will be a confusion for class Derived C to inherit the method BaseMethod(). The confusion is from which class it will inherit. It is the diamond of death in OOPS jargon.
Explain with it's usefulness what is Larger Heap Object?

When an object is created, if the object size is greater than 85000 bytes, it will be created in a separate heap called, Large Object Heap. If the size is lesser than 85000 bytes, it will be created in a heap called, Smaller Object Heap.When the Garbage Collector collects the objects, it will perform the compaction on Small Object Heap for more contiguous free memory. However, in case of Large Object Heap, it will not perform any compaction, as it takes more resources to move the Large Objects.
What is the rule for which you can inherit a base class from C# which is being developed in F#?

If a language is CLS-Compilant(Common Language specifications), and also if the class developed by using CLS specifications, then it can be inherited in another CLS-Compilant language.Both F# and C# are CLS-Compilant languages. So, it is possible to inherit the base class in C# where the base class is developed in F#.
What is serialization and deserialization? Explain their significance.

While sending an object from a source to destination, an object will be converted into a binary/xml format. This process is called serialization .

After it is reached to destination, it will be converted back to original object. This process is called deserialization .

Serialization/deserialization will avoid problems like byte reordering,memory layout etc and gives better performance.

Byte Reordering :
Machines might be of type Big-Endian or Small-Endian. Depends on Endian type, most significant bytes will be stored in left-side or right-side. When an object traverse from One Endian machine to another Endian machine, these bytes needs to be reordered. By serializing/deserializing we are avoiding this.

Memory Layout :
Different programming languages might store the object in different ways. When the object is traversed,it needs to be stored in memory according to language architecture. By serializing/deserializing we can avoid this problem.
Write a lambda expression to add all the natural numbers below five hundred that are multiples of 7 or 11.

var ans =  Enumerable.Range(0, 500).Where(i => i % 7 == 0 || i % 11 == 0).Sum();


Enumerable.Range generates a sequence of integral numbers within a specified range.
In this case it is between 0 to 500. After that inside the Where extension method we are checking if the number is divisible by 7 as well as 11 or not.Which ever number satisfies the condition, we are taking a sum of that.

Result: 27660
What's the difference between Delegate.Invoke(),Delegate.BeginInvoke(),Control.Invoke(),Control.BeginInvoke()?

Delegate.Invoke: Executes synchronously, on the same thread.

Delegate.BeginInvoke: Executes asynchronously, on a threadpool thread.

Control.Invoke: Executes on the UI thread, but calling thread waits for completion before continuing.

Control.BeginInvoke : Executes on the UI thread, and calling thread doesn't wait for completion.
Found this useful, bookmark this page to the blog or social networking websites. Page copy protected against web site content infringement by Copyscape

 Interview Questions and Answers Categories