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

Can you use the ‘throws’ clause to raise an exception?

No, the throws clause cannot be used to raise an exception. The throw statement signals the occurrence of an exception during the execution of a program. When the program encounters a throw statement, the method terminates and returns the error to the calling method.
Explain Dependency Injection with it's advantages with an example

Let us consider the below code snippet

public Class A

{
public int EmpoloyeeID{get;set;}

public string EmpName{get;set;}

public void SomeFunction1(){/...../}

public void SomeFunction2(){/...../}

}
public Class B
{
A objA;
B(){ objA =new B(); }
public void PerformOperationofB(){ foo(objA); }
}
private void foo(A Aobj){
Aobj.SomeFunction1();//do something
Aobj.SomeFunction2();//do something
//rest of the code
}


The program apparently seems nice but has at least the below problems

1) code is not maintainable when it grows
2) Linear coding .. no OO design
3) No or less code reusability
4) Difficult to unit test
5) Highly coupled.

In-Order to mitigate the drawback, what we can do is to delegate the object creation to someone else (say interface). In other words, we are "inverting the control".

Let's see how

interface IMyInterface


{

int EmpoloyeeID{get;set;}

string EmpName{get;set;}

void SomeFunction1();

void SomeFunction2();

}
public Class A : IMyInterface
{
public int EmpoloyeeID{get;set;}
public string EmpName{get;set;}
public void SomeFunction1(){/..... concreate implementation .../}
public void SomeFunction2(){/..... concreate implementation .../}
}
public Class B
{
IMyInterface myInt;
B(IMyInterface myInt){ this.myInt = myInt; }
public void PerformOperationofB(){ foo(myInt); }
}
private void foo(IMyInterface myInt){
myInt.SomeFunction1();//do something
myInt.SomeFunction2();//do something
//rest of the code
}


The advantage of the approach

1) Unit testable code
2) Loosely coupled
3) Code re usability
4) Object creation is happening out the concrete implementation.
5) Maintainable code.
With an example explain Local functions of C# 7.0

Local functions allows us to define a function inside the scope/block of another function. It allows to declare methods and types in block scope just like variables. The concept is very similar to Closure.
e.g.

using System;


namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
void AddNumbersUsingLocalFunction(int a=10, int b=20)
{
Console.WriteLine("Using Local Function : Sum is {0}", a+b);

}
AddNumbersUsingLocalFunction(16);
Console.ReadKey();
}
}
}


As can be figure out that, inside the Main method we have implemented the AddNumbersUsingLocalFunction function. Hence it's scope is bounded inside that block only.
List out some of the features of Local Function of C#7.0

Local functions allows us to define a function inside the scope/block of another function. It allows to declare methods and types in block scope just like variables. Some of the features of Local Functions are listed below -

1) We can use Caller info attributes on parameters
2) Local functions can be generic.
3) Support for optional/default/named arguments
4) Can capture variables (like a lambda)
5) It can be recursive
6) Supports Expression Bodied Function
7) Support for Iterator functions
8) Support for Async functions
Give an example of a Wildl Card based Pattern Matching in C# 7.0

List<object> objCollection = new List<object>() { 10, 20, null, "hello", 12.5 };


foreach (object o in new List<object>() { 10, 20, null, "hello", 12.5 })
{
if (o is *)
{
Console.WriteLine("It's a match for {0}",o);
}
}


It's obvious from the program that, * is the wild card that matches all the types. This is Wildl Card based Pattern Matching in C# 7.0
Let's say we have the below data structure public class Lead { public string LeadFirstName { get; set; } public List<Document> Documents { get; set; } } public class Document { public int DocumentId { get; set; } public string DocumentPath { get; set; } } When we are doing the below stuff Lead lead = new Lead(); lead.LeadFirstName = "Test"; lead.Documents.Add(new Document{ DocumentId = 1, DocumentPath = @"C:\test\abc.doc"}); we are encountering Null Reference exception. What is the root cause of that and how to solve it?

The reason is we are not instantiating the list of documents.We need to initialize the collection. Below is the way to initialize the the collection inside the constructor and to get the program work

public class Lead

{
public Lead()
{
Documents = new List<Document>();
}

public string LeadFirstName { get; set; }
public List<Document> Documents { get; private set; }
}

How to declare the default value of C# variables?

To get the default value of the C# variables, default keyword can be used.
        float f = default(float); // float

Response.Write(f.ToString());
bool b = default(bool); // float
Response.Write(b.ToString());
DateTime d = default(DateTime); // float
Response.Write(d.ToString());


Above code snippet, prints the default value of float, bool and DateTime variable types. Same applies to double, long and other variables.

Thanks
Which of the following is true in c#?

NOTE: This is objective type question, Please click question title for correct answer.
Explain Params Array in C# with an example.

If we want to pass variable number of arguments from calling function to called function, we can use the Params Arrays
e.g.

public class ParamTest


{

static void Main()

{

//calling function

PerformArithmeticOperation(20,10,"+"); //perform addition

PerformArithmeticOperation(20,10,"-"); //perform subtraction

PerformArithmeticOperation(20,10,"*"); //perform multiplication

PerformArithmeticOperation(20,10,"/"); //perform division

}



//called function

public static void PerformArithmeticOperation(params object[] items)

{

var result = 0;

switch (Convert.ToString(items[2])) //items[2] is the operator(s) i.e. +,-,*,/

{

case '+': result = Convert.ToInt32(items[0]) + Convert.ToInt32(items[1]); break;

case '-': result = Convert.ToInt32(items[0]) - Convert.ToInt32(items[1]); break;

case '*': result = Convert.ToInt32(items[0]) * Convert.ToInt32(items[1]); break;

case '/': result = Convert.ToInt32(items[0]) / Convert.ToInt32(items[1]); break;

default: Console.WriteLine("No such operation available");

}

Console.WriteLine(result);

}

}


We also can send no arguments. If we send no arguments, the length of the params list is zero.
Explain the importance of Using keyword and Using Statement in C#

In C# parlance, Using can be use in two ways

a) As a directive where it's behavior will be as inclusion of a namespace. e.g.

using System; //import namespace

using System.IO;
using Item = System.Collections.Generic; //creating alias for namespace
namespace UsingNamespaceDemo
{
public class TestUsingClass
{
//observe Item.List where Item is an alias of System.Collections.Generic namespace
var intItemList = new Item.List<int>(){1,2,3,4,5};
foreach(var item in intItemList) Console.WriteLine(item);
}
}


b)As a statement that can only be used with types that implement IDisposable interface.
e.g.
string connString = "Data Source=abc;Integrated Security=SSPI;Initial Catalog=db;";

using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT * FROM tblTest";
conn.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
Console.WriteLine("{0}", dr.GetString(0));
}
}

It can also be consider as a syntactic sugar(short hand version) for try/finally block e.g.
using (SqlConnection conn = new SqlConnection(connString))

{
//do something
}
is same as

SqlConnection conn = new SqlConnection(connString);

try
{
//do something
}
finally
{
if(conn != null)
{
conn.Dispose();
}
}

What will be the output of i and how many times it will be printed?

NOTE: This is objective type question, Please click question title for correct answer.
What object can help you maintain data across users?

NOTE: This is objective type question, Please click question title for correct answer.
Which of the below is correct format of Jagged array?

NOTE: This is objective type question, Please click question title for correct answer.
Null Coalescing type in C# used with nullable?

NOTE: This is objective type question, Please click question title for correct answer.
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