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

Write a program that implements dynamic polymorphism.

namespace DynamicPolymorphism

{
public abstract class Animal
{
public abstract void Run();
}

public class Tiger : Animal
{
public override void Run()
{
Console.WriteLine("Tiger runs at 80 Km/hr");
}
}

public class Lion : Animal
{
public override void Run()
{
Console.WriteLine("Lion runs at 60 Km/hr");
}

}

class Program
{
static void Main(string[] args)
{
Animal objAnimal = new Lion();
objAnimal.Run();
objAnimal = new Tiger();
objAnimal.Run();
Console.Read();
}
}
}


Here i have a abstract class called Animal. This Animal class contains an abstract method called Run(). Note that here method declaration is only written and not implementation.
Now I have two classes called Tiger and Lion. These two classes inherits from base class Animal.
  public class Lion : Animal

public class Tiger : Animal

I override the base class Run() method in my Lion and Tiger class.
The keyword override is used to override the base class function.
public override void Run() ---> in Tiger and Lion class overrides the base class Run() function.

I am printing in Lion class
 Console.WriteLine("Lion runs at 60 Km/hr");

I am printing in Tiger class
 Console.WriteLine("Tiger runs at 80 Km/hr");

In program class the real implementation is done.
At first I am creating base class reference pointing to derived class.
In first line I am creating Animal class reference pointing to Lion class using "new" keyword
Animal objAnimal = new Lion();
Then I am calling Run() function, now it calls the Run() function of Lion class and executes the line
 Console.WriteLine("Lion runs at 60 Km/hr"); 

Now I am reassigining or changing the reference from Lion class to Tiger class . Note that I am using the same object "objAnimal"
 objAnimal = new Tiger();   
Then I am calling Run() function, now it calls the Run() function of Tiger class and executes the line
 Console.WriteLine("Lion runs at 60 Km/hr"); 

Write a code snippet for swapping two variables without using third variable..

For Integers
           int i = 10;

int j = 15;
i = i + j;
j = i - j;
i = i - j;
Console.WriteLine("The swapped values are i={0},j={1}", i, j);

In the above code I am adding the two variables. Here i+j = 25 and assigning to i. Now I am subtracting j from i which is 25-15 is equals 10 and assigning to j. In third line I am subtracting j (currently it is 10) from i and assigning to i. So here 25-10=15. At last we will be having the values swapped i=15 and j=10.

For String:
--------------
I used replace function here. If any one has better solution then this please let me know.

            string a = "Naga";

string b = "Sundar";
a = a + b;
b = a.Replace(b, "");
a = a.Replace(b, "");
Console.WriteLine("The swapped values are a={0},b={1}", a, b);

I am using the same logic that I used for Integers. I am appending string "a" and "b" and saving it in "a". Now the variable "a" contains text "Nagasundar". From here I am using replace function and eliminates "Sundar". Now string "b" contains "Naga". Once again I am using replace function so that I am removing string "b" (currently "Naga") from "a". So I am getting "Sundar" in variable "a" and "Naga" in variable "b"
What is type safe object in DotNet that but can be pointed to more than one function at a time and can be invoked explicitly?

NOTE: This is objective type question, Please click question title for correct answer.
How can you prevent the class from being inherited by other classes without using "Sealed" keyword.?

By declaring base class constructor as Private we can avoid that class being inherited by another class. When we create the object for the derived class the base class constructor called automatically and executed. Hereit cannot be executed due to its protection level. See the code snippet:

namespace Example

{
class Base
{
private Base()
{
}
public void Test()
{
Console.WriteLine("Test");
}
}
class Program : Base
{
static void Main(string[] args)
{
Program pObj = new Program();
pObj.Test();
}
}
}
If we run the above code we get the following error :

'Example.Base.Base()' is inaccessible due to its protection level'
What is boxing and unboxing in C#.NET? Explain briefly with sample code.

Boxing is a process of converting value type variable to reference type or object type. The boxing can be done implicitly or explicitly.
Implicit boxing means the type casting or conversion can be done automatically where as explicitly can be done by manual type casting.

Unboxing is an explicit conversion from reference type to a value type. It has to be done explicitly.

Please look at the following example:

static void Main(string[] args)

{
#region Boxing
int intVariable = 10;

object objImplicitBoxing = intVariable; //Implicit Boxing
object objExplicitBoxing = (object)intVariable; //Explicit Boxing

Console.WriteLine(string.Format("Implicit Boxing {0}",objImplicitBoxing));
Console.WriteLine(string.Format("Explicit Boxing {0}",objExplicitBoxing));
#endregion

#region Unboxing
int iUnbox = (int)objImplicitBoxing; //Explicit Unboxing
Console.WriteLine(string.Format("Explicit Unboxing {0}",iUnbox));
#endregion
}


From the above code:

object objImplicitBoxing = intVariable;   


The above line indicates assigining the integer value to object DIRECTLY.


object objExplicitBoxing = (object)intVariable;


The above line type casts the integer value to object and assigning to another object.

int iUnbox = (int)objImplicitBoxing;	


The above line type casts the object to Integer value and assigning to Integer variable.
what are the properties of datatable?

DataTable is a class that contains data in row column format. Some of the properties of datatable are


TableName         -- Denotes the name of the DataTable.

DataSet -- Gets the dataset for the table.
DefaultView -- Gets the view of datatable with RowFilter condition etc.,
ROWS -- Get all rows of the table.
Column -- Denotes all columns of the table
ChildRelation -- Gets the collection of child relations for the data table
ParentRelation -- Gets the collection of parent relations for the data table
Constrints -- Gets the collection of constraints maintained by the table
PrimaryKey -- Gets or Sets an array of columns that function as primary key for
the table.


Apart from this we have the properties such as

Extended Properties, HasErrors, IsInitialized, locale, MinimumCapacity, Prefix, RemotingFormat, Site

Write a code snippet that implements Virtual keyword ,overrides the virtual method in C#.

A virtual method can be redefined.The virtual keyword is used to modify a method and allow it to be overridden in a derived class. We can add derived types without modifying the rest of the program. The runtime type of objects thus determines behavior.

Here is the code snippet :

class Base

{
public virtual void FncOverride()
{
Console.WriteLine("Base Override");
}
}

class Derived : Base
{
public override void FncOverride()
{
Console.WriteLine("Derived Override");
}
}
class Program : Derived
{
static void Main(string[] args)
{
// Compile-time type is Base.
// Runtime type is also Base.
Base bObj = new Base();
bObj.FncOverride();

// Compile-time type is Base
// Runtime type is Derived.
Base bdObj = new Derived();
bdObj.FncOverride();
}
}


In the above code the base class has FncOverride() method with Virtual keyword and overriding that method in Derived class. In my Main() function I am calling the base class FncOverride() method in following way
     Base bObj = new Base();

bObj.FncOverride();

Now the calling function will be known to compiler at compile time itself.
But when accessing the method like this:
  Base bdObj = new Derived();

bdObj.FncOverride();

This time the derived class function will be called. And the compiler decides at run time that which method should be invoked.

While executing the above code we get
Base Override

Derived Override

What are the differnt categories of variables available in C#?

C# has seven types of variables.

They are

local variables           -- Variables declared inside method or function.

instance variables -- Declares at class level scope
static variables -- which contains Static keyword before variable data type.
array elements, -- Array variable. Contains sequence of memory locations.
value parameters, -- Value type variable passed in parameters
reference parameters -- Reference type variable passed in parameters
output parameters -- Out type variable passed in parameters


There is no global variable in C#. Because it breaches the encapsulation concept.

class Program

{
int VarClassScope = 42;
static int VarStatic = 5;

public void FncVariables(int VarValueParam, ref int VarRefParam, out int VarOutParam)
{
VarOutParam = 100;
VarRefParam = 50;
VarValueParam = 25;
}

static void Main(string[] args)
{
Program pObj = new Program();
int VarFunctionScope = 23;
int[] VarArrVariable = new int[1];
VarArrVariable[0] = 22;
Console.WriteLine("Class variable = " + pObj.VarClassScope);
Console.WriteLine("Function variable = " + VarFunctionScope);
Console.WriteLine("Static variable = " + VarStatic);
Console.WriteLine("Array Element variable = " + VarArrVariable[0]);

int VarOutParam = 10; //No use of initializing here for OUT
int VarRefParam = 10;
int VarValueParam = 10;
pObj.FncVariables(VarValueParam, ref VarRefParam, out VarOutParam);

Console.WriteLine("Value Param Variable = " + VarValueParam);
Console.WriteLine("Reference Param Variable = " + VarRefParam);
Console.WriteLine("Out Param Variable = "+ VarOutParam);

Console.Read();
}

}


In the above code I am initializing all kinds of variables. Note the line

 pObj.FncVariables(VarValueParam, ref VarRefParam, out VarOutParam);

I am calling the "FncVariable"s function which accepts value, referene and out type variables. Before calling the function all variables have value 10.
But after calling the "FncVariable"s function, value type variable remains unchanged but ref and out type variables changed.

The output is

Class variable = 42

Function variable = 23
Static variable = 5
Array Element variable = 22
Value Param Variable = 10
Reference Param Variable = 50
Out Param Variable = 100

Write a program in C# using Linq that prints count of leap years in 20th century ?

We have to note that they are not asking to print all the leap years, but they are asking only the number of leap years. Now 20th century means the years between 1900 and 1999. Here the code :

class Program

{
public int NoOfLeapYear()
{

int cntYears = (from year in Enumerable.Range(1900, 100)
where DateTime.IsLeapYear(year) == true
select year).Count();
return cntYears;

}
static void Main(string[] args)
{
try
{
Program pObj =new Program();
Console.WriteLine(string.Format("No of LeapYear between 1900-1999 is {0}",pObj.NoOfLeapYear()));
Console.Read();
}
catch (Exception exx)
{
throw;
}
}
}


In the NoOfLeapYear function I am using Enumerable.Range() method to get all the values between the specific range. Enumerable.Range() method accepts two parametes. In which first parameter is the starting number and second parameter indicates count.

Here important point to be notes is
Enumerable.Range(1900, 100)


this code will return the value from 1900 to 1999. Starting first value as 1900 the 100th value is 1999. These are the years of 20th century.
In "where" condition I am using Leap year functio of DateTime class and checking for every year between 1900 and 2000.
In Select statement I am using Count() to get the total number. Since Count() return integer I declared "cntYears" as Integer. (No type casting required).

The output of above code is
No of LeapYear between 1900-1999 is 24

Write a C# program that prints the Prime numbers between 1 and 100 and also print the count of prime numbers between 1 and 100. (Try to avoid inbuild functions)

Prime numbers are the numbers which are divisible by 1 and that number itself. Here is the code:
class Program

{
public bool IsPrimeNumber(int num)
{
bool bPrime = true;
int halfNo = num / 2;
int i = 0;

for (i = 2; i <= halfNo; i++)
{
if ((num % i) == 0)
{
bPrime = false;
break;
}
}

if (bPrime == true)
chk++;

return bPrime;
}
static void Main(string[] args)
{
Console.WriteLine("List of prime numbers between 0 to 100");
Program pObj = new Program();
for (int val = 1; val <= 100; val++)
{
if (pObj.IsPrimeNumber(val) == true)
{
Console.Write(string.Format("{0,8:n}\t", val));
}
}


Console.WriteLine(string.Format("\nTotal count " + chk));
}
}


In the above code I am creating a for loop from 1 to 100 in Main() function. Inside the for loop I am calling ISPrimeNumber method which returns boolean.

In IsPrimeNumber method I have declared bPrime variable and initialized to true. Then I am getting the half of the passed value. Because the factors will not be greater then half of the given number.


Say for example : The number is 20

then 20/2 = 10

so the for loop in IsPrimeNumber() method runs 10 times in this scenario. Here I am checking reminder for each iteration of i. i.e like (20%2, 20%3,..)

for 20 ---> 20%2 = 0 so I am using break stement to exit the for loop. Since first iteration itself satisfies the condition, no need to check the rest.

If we take 23

then 23/2 = 11.

so the for loop in IsPrimeNumber() method runs 11 times.

for 23---> 23%2 !=0,23%3 !=0,23%4 !=0,23%5 !=0,23%6 !=0,23%7 !=0,23%8 !=0,23%9 !=0,23%10 !=0,23%11 !=0. So this number is Prime number.

To get the count of prime numbers I am using "chk" variable and incremented it when prime number is encountered


The output will be:

  1.00            2.00            3.00            5.00            7.00

11.00 13.00 17.00 19.00 23.00
29.00 31.00 37.00 41.00 43.00
47.00 53.00 59.00 61.00 67.00
71.00 73.00 79.00 83.00 89.00
97.00
Total count 26

Write a C# sharp Program to check wheather the given string is Palindrome or not. (Ex: LEVEL is palindrome).Don't use inbuild string functions.

PALINDROME string is sequence of letters that is the same forward as backward. Example is LEVEL.

class Program

{
public bool IsPalindrome(string sInput)
{
int iLengthofInput = 0;

//Find Length of the string.
foreach(char chr in sInput)
iLengthofInput++;

char[] sArrReverse = new char[iLengthofInput];

int iIncr =iLengthofInput-1;
foreach(char chr in sInput)
{
sArrReverse[iIncr] = chr;
iIncr--;
}

string sRevString = new string(sArrReverse);

#region AnotherWay for string initializng
//string sRevString = "";
//for(int i = 0; i < iLengthofInput; i++)
//{
// sRevString += sArrReverse[i];
//}
#endregion

if (sRevString == sInput)
return true;
else
return false;

}
static void Main(string[] args)
{
Program pObj = new Program();
Console.WriteLine(pObj.IsPalindrome("LEVEL");
Console.Read();
}
}


In the above code I am finding the length of the string. For example : LEVEL - length is 5.

char[] sArrReverse = new char[iLengthofInput];


int iIncr =iLengthofInput-1;
foreach(char chr in sInput)
{
sArrReverse[iIncr] = chr;
iIncr--;
}

In the above code I am creating the arrary called "sArrReverse" and initializing with length of input string.
In Foreach loop I am assigning values of input string in reverse order. So now sArrReverse contains "LEVEL" which is reverse form of original input string "LEVEL".
I am creating a string "sRevString" and initializing with "sArrReverse" value in the following code
 string sRevString = new string(sArrReverse);

OR
string sRevString = "";

for(int i = 0; i < iLengthofInput; i++)
{
sRevString += sArrReverse[i];
}


Using If condition I am checking both strings and returning the value depends on condition.
What is the difference between ArrayList and Generic List in C#?

Generic collections are TypeSafe at compile time. So No type casting is required. But ArrayList contains any type of objects in it. Here is the code snippet.

namespace Example

{
class Program
{

static void Main(string[] args)
{

ArrayList list = new ArrayList();
list.Add("hello");
list.Add(new Program()); // Oops! That's not meant to be there...
list.Add(4);

foreach (object o in list)
{
Console.WriteLine(o.ToString());
}


List<string > lstString = new List<string>();
lstString.Add("ABCD");
lstString.Add(new Program()); //Compiler error
lstString.Add(4); // Compiler Error


foreach (object o in lstString)
{
Console.WriteLine(o.ToString());
}
}

}


In the above code I am using "list" obejct of ArralyList type and adding all types of values such as string, int, object of Program class. When printing I am considering everything as object and converting it into string. This part of code alone will print

hello

ConsoleApplication7.Program
4


But when coming to the second part "lstString" which is object of List<string> object will not compile when control comes to the following lines

             lstString.Add(new Program());   //Compiler error

lstString.Add(4); // Compiler Error



The output will be
Error:
The best overloaded method match for 'System.Collections.Generic.List<string>.Add(string)' has some invalid arguments.

What is Lamda Operator? Explain with code.

Lamda expression are concise way to represent an anonymous method that we can use to create delegates or expression tree types. Lambda expression is an inline delegate introduced with C # 3.0 language.

 static void Main(string[] args)

{
#region Using Lamda
int[] Marks = { 100,54,35,98,62,85,49 };


var FailMarks = Marks.Where(Fail => Fail < 50);

foreach (int failMarks in FailMarks)
Console.WriteLine(string.Format("Fail Marks are using LAMDA {0}", failMarks));
#endregion


#region Using Delegate
var delegateFail = Marks.Where(delegate(int x)
{
return (x < 50);
})
.ToList();


foreach (int failMarks in delegateFail)
Console.WriteLine(string.Format("Fail Marks are using DELEGATES {0}", failMarks));
#endregion
}


In the above code I am having integer array of marks ranging from 1-100. I need to print the marks which are lesser then 50 that is Fail. In first part I achieved using Lamda operator by a condition less then 50. In second part I created an anonymous delegate and checking the conditon.

The output will be
Fail Marks are using LAMDA 35

Fail Marks are using LAMDA 49
Fail Marks are using DELEGATES 35
Fail Marks are using DELEGATES 49

What is the differnence between StringBuilder and String?

"String" is immutable. That is we can not change the value of string once assigned. If we assign the value to string inside loops then each time the object will be destroyed and created again.
"StringBuilder" is mutable. That is the object will not be recreated if there is any modification, instead it will append the new value with old value. Consider the following piece of code:

   StringBuilder sbMutalble = new StringBuilder();

string sImmutable = "1";

for (int val = 1; val <= 9; val++)
{
sImmutable += val;
sbMutalble.Append(val);
}


Here the string varaible "sImmutable" will be recreated for 10 times, because in each time we are adding a new value to the existing value.
In case of stringbuilder the varaible "sbMutable" will not be recreated instead it will append the new values
What is the output of the following code snippet? class Program { public string GetMarks(int Marks) { if ((Marks >= 100) && (Marks < 80)) return "Very good"; else if ((Marks >= 80 && Marks < 100)) return "good"; else if (Marks <= 60) return "failure"; else if (Marks >= 60 && Marks < 90) return "good"; else return "No records found"; } static void Main(string[] args) { Program pObj = new Program(); Console.WriteLine(pObj.GetMarks(60)); } }

The output will be "Failure"

Here I used If-Else condition. As per if else logic if "if" part gets true then all other else parts are omitted eventhough the conditon might true.
Here the last condition "if (Marks >= 60 && Marks < 90)" satisfies condition if we give value 60 but third condition "if (Marks <= 60)" also gets true. Since
thrid condition itself gets true fourth condition will not be executed though it is true as well.
Does Private methods also gets inherited in C#?

NOTE: This is objective type question, Please click question title for correct answer.
What is the difference between Dictionary and Hash table?

Dictionary

Trying to access an in existent key gives runtime error in Dictionary.
Dictionary is a generic type
Generic collections are a lot faster as there's no boxing/unboxing
Dictionary public static members are thread safe, but any instance members are not guaranteed to be thread safe.
Dictionary is preferred than Hash table

Hash table

Trying to access an in existent key gives null instead of error.
Hash table is a non-generic type
Hash table also have to box/unbox, which may have memory consumption as well as performance penalties.
Hash table is thread safe for use by multiple reader threads and a single writing thread
This is an older collection that is obsoleted by the Dictionary collection. Knowing how to use it is critical when maintaining older programs.
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