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

Which property of the textbox cannot be changed at runtime ?

Locked Property of the textbox is the property that cannot be changed at runtime.

Example:

[BrowsableAttribute(false)]

public bool Locked { get; set; }

How do I simulate optional parameters to COM calls ?

To simulate optional parameters to COM calls, You must use the Missing class and pass Missing.Value (in System.Reflection) for any values that have optional parameters.
How do you directly call a native function exported from a DLL ?

Below is a quick example of the DllImport attribute in action:


using System.Runtime.InteropServices;
class C
{
[DllImport("user32.dll")]
public static extern int MessageBoxA
(int h, string m, string c, int type);
public static int Main()
{
return MessageBoxA(0, "Hello World!", "Caption", 0);
}
}


This example shows the minimum requirements for declaring a C# method that is implemented in a native DLL. The method C.MessageBoxA() is declared with the static and external modifiers, and has the DllImport attribute, which tells the compiler that the implementation comes from the user32.dll, using the default name of MessageBoxA. For more information, look at the Platform Invoke tutorial in the documentation.
Why are there five tracing levels in System.Diagnostics.TraceSwitcher ?

Five levels range from None to Verbose, allows to fine-tune the tracing activities.This is because, the tracing dumps can be quite verbose and for some applications that are constantly running you run the risk of overloading the machine and the hard drive there.
While doing Method Overloading, return type must be same. True or False ?

NOTE: This is objective type question, Please click question title for correct answer.
In Method Overriding, the return type can be changed while overriding it ? Yes or No

No.

In Method Overriding , the signature of the method cannot change. Everything must remains same only the implementation in the derived class will differ.



Thanks and Regards
Akiii
By default, what is the access specifier of member variables and member function of a class ?

NOTE: This is objective type question, Please click question title for correct answer.
When any method is declared as abstract then it is necessary to declare the class as abstract. True or False ?

True.

If any method is declared as abstract then it is necessary to declare the class as abstract also otherwise there will be an compile time error.

For example :
public abstract class clsbase

{
public abstract int subs(int num1, int num2);
}


Try removing the abstract keyword before the class. You will get an error !


Thanks and Regards
Akiii
Can we declare abstract keyword on fields in a class ?

No we cannot.

For example :-

public abstract class clsbase

{
public abstract string str = "Akiii";
}


executing the code will results in the following error :-
Error 1 The modifier 'abstract' is not valid on fields. Try using a property inste ad.


Thanks and Regards
Akiii
Which condition has high performance among this : int i = 5; 1 . if ( i == 5) { } 2. if ( 5 == i ) { }

NOTE: This is objective type question, Please click question title for correct answer.
Can we define two main methods in an application ?

NOTE: This is objective type question, Please click question title for correct answer.
Can a "struct" contain parameter-less constructor or default constructor ?

No, a "struct " cannot contain a parameter-less constructor or default constructor. The default constructor is implicit for all structures and cannot be overridden. It simply sets all of the fields in the structure to their default values.

For example :-

struct st

{
public st()
{

}

string name;

public st(string name)
{
this.name = name;
}
}


Try to compile the above code and you will get an error like below:-

Structs cannot contain explicit parameterless constructors

It is not possible for one structure to inherit functionality from another structure or class. True or False ?

NOTE: This is objective type question, Please click question title for correct answer.
Can we create a class private?

No, we can not create a class private, it will give runtime error.

Example:
private class <classname>

{
}

compile time error. class can not be defined as private, protected and internal.
What is difference between throw and throw ex?

When you use throw ex to throw exception, it will update stack trace but in throw it will not update stack trace.

Example:
Class cls

{
public static void Main(string[] args)
{
try
{

function3();
Console.WriteLine("Catch Ex"); Console.ReadLine();

}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace); Console.ReadLine();
}
}

public static void function3()
{
try
{
function2();
}
catch (Exception ex)
{
throw;
}
}
public static void function2()
{
try
{
function1();
}
catch (Exception ex)
{
throw;
}
}
public static void function1()
{
try
{
int i = 0;
int j = 2 / i;
}
catch (DivideByZeroException ex)
{
throw;
}
}
}

How will you merge strings in C# without using a loop?

Suppose, we have some data in the form of string array as under

new string[] { "Hello,", "How", "Are", "You" }

We need to write a C# program that will concatenate the string and will generate the below output
Hello, How Are You

Solution 1: Using Aggregate function
var input = new string[] { "Hello,", "How", "Are", "You" };

var result = input.Aggregate((a, b) => a + " " + b);
Console.WriteLine(result);


Solution 2: Using Join function
var input = new string[] { "Hello,", "How", "Are", "You" };

var result = string.Join(" ", input);
Console.WriteLine(result);

What is the purpose of ZIP extension method? Explain with example.

The new ZIP extension method introduced in C#4.0 merges two collection sequences by using a predicate function.It is a Combining operator.It combines items from one collection with items from second that are in the same position in the collection.

If Collection A has N items and Collection B has N items (N = 1, 2, 3, 4...), the ZIP extension method will perform the operation as A[N] with B[N].


Let us see an example

Sample input

List<int> firstCollection = new List<int> { 11,12,13,14,15 };
List<int> secondCollection = new List<int> { 6,7,8,9,10 };


Aim:

To perform x[i] + y[i]

Solution using ZIP extension method



var firstCollection = new List<int> { 11,12,13,14,15 };
var secondCollection = new List<int> { 6,7,8,9,10 };

firstCollection
.Zip(secondCollection, (a, b) => a + b)
.ToList()
.ForEach(i => Console.WriteLine(i));



Result


17
19
21
23
25


Explanation:

We are merging the two sequences by using the predicate function ((a, b) => a + b) and using the Foreach extension method performing the display action on each element.
How to implement IN clause in LINQ/LAMBDA Query expression?Explain with an example.

This can be done using the "Contains" extension method. Example follows.

Suppose we have a person class as under

public class Person

{
public string PersonName { get; set; }
public string JobTitle { get; set; }

public override string ToString()
{
return "Person Name: " + PersonName + " JobTitle:" + JobTitle;
}
}


Then populate the Person collection as under

private static List<Person> PreparePersonCollection()

{
List<Person> lstPersonCollection = new List<Person>();
lstPersonCollection.Add(new Person { PersonName = "Amitav Sen", JobTitle = "Design Engineer" });
lstPersonCollection.Add(new Person { PersonName = "Bhavini Dey", JobTitle = "Software Engineer" });
lstPersonCollection.Add(new Person { PersonName = "Debasis Basu", JobTitle = "Software Engineer" });
lstPersonCollection.Add(new Person { PersonName = "Kartik Moin", JobTitle = "Lead Engineer" });
lstPersonCollection.Add(new Person { PersonName = "Shahjahan Khan", JobTitle = "Technical Lead" });

return lstPersonCollection;
}


Suppose we want to get the list of Person who has job Title as "Design Engineer", "Software Engineer".

The complete query will be as under

List<Person> source = PreparePersonCollection();


string[] strJobTitleToInclude = new string[] { "Design Engineer", "Software Engineer" };

source
.Where(i=>strJobTitleToInclude.Contains(i.JobTitle))
.ToList()
.ForEach(i => Console.WriteLine(i.ToString()));


Output

Person Name: Amitav Sen JobTitle:Design Engineer

Person Name: Bhavini Dey JobTitle:Software Engineer
Person Name: Debasis Basu JobTitle:Software Engineer

How to implement NOT IN clause in LINQ/LAMBDA Query expression?Explain with an example.

This can be done by negating the "Contains" extension method . Example follows.

Suppose we have a person class as under

public class Person

{
public string PersonName { get; set; }
public string JobTitle { get; set; }

public override string ToString()
{
return "Person Name: " + PersonName + " JobTitle:" + JobTitle;
}
}


Then populate the Person collection as under

private static List<Person> PreparePersonCollection()

{
List<Person> lstPersonCollection = new List<Person>();
lstPersonCollection.Add(new Person { PersonName = "Amitav Sen", JobTitle = "Design Engineer" });
lstPersonCollection.Add(new Person { PersonName = "Bhavini Dey", JobTitle = "Software Engineer" });
lstPersonCollection.Add(new Person { PersonName = "Debasis Basu", JobTitle = "Software Engineer" });
lstPersonCollection.Add(new Person { PersonName = "Kartik Moin", JobTitle = "Lead Engineer" });
lstPersonCollection.Add(new Person { PersonName = "Shahjahan Khan", JobTitle = "Technical Lead" });

return lstPersonCollection;
}


Suppose we want to get the list of Person who does not has job Title as "Design Engineer", "Software Engineer".

The complete query will be as under

List<Person> source = PreparePersonCollection();


string[] strJobTitleToInclude = new string[] { "Design Engineer", "Software Engineer" };

//Linq Version

(from s in source
where !strJobTitleToInclude.Contains(s.JobTitle)
select s)
.ToList()
.ForEach(i => Console.WriteLine(i.ToString()));

//Lambda Version
source
.Where(i => !strJobTitleToInclude.Contains(i.JobTitle))
.ToList()
.ForEach(i => Console.WriteLine(i.ToString()));


Output

Person Name: Kartik Moin JobTitle:Lead Engineer

Person Name: Shahjahan Khan JobTitle:Technical Lead

What is the purpose of Tuple? Explain with example.

C#4.0 has introduce a new feature call Tuple.It is useful when we want to return more than one value from a method or function.

Let us look the below example

class Program

{
static void Main(string[] args)
{

var returnValue = Calculate();

string format =
"Addition: {0}" + Environment.NewLine +
"Subtraction: {1}" + Environment.NewLine +
"Multiplication: {2}" + Environment.NewLine +
"Division: {3}";
string result = string.Format(format, returnValue.Item1, returnValue.Item2, returnValue.Item3, returnValue.Item4);
Console.WriteLine(result);
Console.ReadKey(true);
}

private static Tuple<int,int,int,int> Calculate()
{
int num1 = 20;
int num2 = 10;
return Tuple.Create(num1+num2,num1-num2,num1 * num2,num1/num2);
}
}


As can be seen that using Tuple we can return multiple values from the function/method in a better and readable way.
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