Thursday, May 8, 2014

C Sharp Interview Questions Volume I

C# Interview Questions


What's the difference between IEnumerable<T> and List<T> ?


1. IEnumerable is an interface, where as List is one specific implementation of IEnumerable. List is a class.

2. FOR-EACH loop is the only possible way to iterate through a collection of IEnumerable, where as List can be iterated using several ways. List can also be indexed by an int index, element can be added to and removed from and have items inserted at a particular index.

3. IEnumerable doesn't allow random access, where as List does allow random access using integral index.

4. In general from a performance standpoint, iterating thru IEnumerable is much faster than iterating thru a List.
If I am not wrong, using Enumerator.MoveNext() also we can traverse through a collection of IEnumerable.
A Class is abstract Data Type becauses it specifies what data members and member functions(methods) contain in it(class) ,but wont provide information on how those are implemented.
Abstract class is a class which contain both abstract & non abstract members (Abstract Methods declaration). When ever you want to implement a abstract method from abstract class you need to inherit the abstract class first & then implement the abstract method in the derived class. Abstract class should be a base class & we can not derived class as a abstract class.
Let us consider there is a scenario that you have one Interface,in that there are so many defined methods(not implemented). Here you have to derive a class from that interface in this situation you need to implement all the methods of that interface but you don't know all the methods actual implementation, you know only one method implementation that you need, so for all that unknown methods you just put a key word "abstract" in your class and leave them, i hope every body know the abstract protocol, i.e if you declare one method as abstract in your class that class is an abstract class so you must declare that class as abstract class.remaining all routine things are discussed above by our friends............

C# 4.0 New Features


What are the new features introduced in c# 4.0?

This is very commonly asked c# interview question. This question is basically asked to check, if you are passionate about catching up with latest technological advancements. The list below shows a few of the new features introduced in c# 4.0. If you are aware of any other new features, please submit those using the from at the end of this post.

1. Optional and Named Parameters
2. COM Interoperability Enhancements
3. Covariance and Contravariance
4. Dynamic Type Introduction

Explicit Interface Implementation

This C# Interview Question was asked my a member of this blog. Please refer to the example code below.

How to implement the void Method() of the interface in the following case ?

class B 
{
   public void Method() 
   {
       // some code here
       //...
   }
}

Youtube video on Explicit Interface Implementation

 

interface I 
{
   void Method();
}

class D : B, I 
{
   // how to implement the void Method() of the interface
   // public void I.Method() { ... }
} 

To implement void Method, we use explicit interface implementation technique as shown below.

using System;
namespace SampleConsole
{
class Program
{
   static void Main()
   {
      //To Call Class B Method
      D d = new D();
      d.Method();

      //To Call the Interface Method
      I i = new D();
      i.Method();

      //Another way to call Interface method
      ((I)d).Method();
   }
}
class B
{
   public void Method()
   {
      Console.WriteLine("Void Method - B");
   }
}
interface I
{
   void Method();
}
class D : B, I
{
   void I.Method()
   {
      Console.WriteLine("Void Method - I");
   }
} 
}

Difference between EXE and DLL


1. .EXE is an executable file and can run by itself as an application, where as .DLL is usullay consumed by a .EXE or by another .DLL and we cannot run or execute .DLL directly.

2. For example, In .NET, compiling a Console Application or a Windows Application generates .EXE, where as compiling a Class Library Project or an ASP.NET web application generates .DLL. In .NET framework, both .EXE and .DLL are called as assemblies.

3. .EXE stands for executable, and .DLL stands for Dynamic Link Library
DLL - Dynamic Link Library



An ActiveX Dll runs is an in process server running in the same memory space as the client process.



EXE – Executable File


An ActiveX Exe is an out of process server which runs in its own separate memory space.

Advantages of ActiveX Dll
-------------------------
1) An in-process component shares its client’s address space, so property and method calls don’t have to be marshaled. This results in much faster performance.

Disadvantages of ActiveX Dll
----------------------------
1) If an unhandled error occurs it will cause the client process to stop operating.

Advantages of ActiveX Exe
-------------------------
1) The component can run as a standalone desktop application, like Microsoft Excel or Microsoft Word, in addition to providing objects.
2) The component can process requests on an independent thread of execution, notifying the client of task completion using events or asynchronous call-backs. This frees the client to respond to the user.
3)If an error occurs the client processes can continue to operate.

Disadvantages of ActiveX Exe
----------------------------
1) Generally slower than an ActiveX dll alternative

Unit Test private method in C# .NET


This is a very common c# interview question. As a developer all of us know, how to unit test public members of a class. All you do is create an instance of the respective
class and invoke the methods using the created instance. So, unit testing public methods is very straight forward, but if the method that we want to unit test is a private method, then we cannot access it outside the class and hence cannot easily unit test it. 

Consider the example class shown below. CalculatePower() method with in the Maths class is private and we want to unit test this method. Also, note that CalculatePower() is an instance private method. In another articel we will discuss the concept of unit testing a private static method. Microsoft's unit testing assembly contains a class called PrivateObject, which can be used to unit test private methods very easily. Microsoft.VisualStudio.TestTools.UnitTesting.PrivateObject is the fully qualified name. Click here, to read an articel on, unit testing a private static method with an example.

public class Maths
{
   private int CalculatePower(int Base, int Exponent)
   {
      int Product = 1;

      for (int i = 1; i <= Exponent; i++) 
      { 
         Product = Product * Base; 
      } 
      return Product; 
   } 
} 

To unit test this method, We create an instance of the class and pass the created instance to the constructor of PrivateObject class. Then we use the instance of the PrivateObject class, to invoke the private method. The fully completed unit test is shown below. 

[TestMethod()] 
public void CalculatePowerTest() 
{ 
   Maths mathsclassObject = new Maths(); 
   PrivateObject privateObject = new PrivateObject(mathsclassObject);
   object obj = privateObject.Invoke("CalculatePower", 2, 3);  
   Assert.AreEqual(8, (int)obj); 
}

Unit Testing a private static method in C# .NET


In the previous article we have seen how to unit test private instance methods. In this article we will see unit testing static private methods. If you have not read the previous article on unit testing private instance methods, I would strongly recomend you to read, before you proceed with this article.

In general, to unit test a static public method, we invoke the respective method using the
class name in our test method. We then simply check for the expected and actual output. However, when it comes tounit testing a static private method, we cannot do the same, as the private members are not available outside the class. To make the process of unit testing static private members easier, microsoft unit testing framework has provided PrivateType class.

In the example below, CalculatePower()is a private static method. The purpose of this method is to calculate the value, when a given number is raised to a certain power. For example 2 to the power of 3 should return 8 and 3 to the power of 2 sholuld return 9. So to unit test this method we create the instance of PrivateType class. To the constructor of the PrivateType class we pass the type of the class that contains the private static method that we want to unit test. We do this by using the typeof keyword. ThePrivateType instance can then be used to invoke the private static method that is contained with in the Maths class. The Maths class that contains the static private CalculatePower()method and the unit test are shown below.

public class Maths
{
   private static int CalculatePower(int Base, int Exponent)
   {
      int Product = 1;


      for (int i = 1; i <= Exponent; i++)
      { 
         Product = Product * Base; 
      } 
      return Product; 
   } 
} 

[TestMethod()]
public void CalculatePowerTest()
{
   PrivateType privateTypeObject = new PrivateType(typeof(Maths));
   object obj = privateTypeObject.InvokeStatic("CalculatePower", 2, 3);

   Assert.AreEqual(8, (int)obj);
}

Why C# does not support multiple class inheritance

Why C# does not support multiple class inheritance?
or
What are the problems of multiple class inheritance?

C# does not support multiple class inheritance because of the diamond problem that is associated, with multiple class inheritance. Let us understand the diamond problem of multiple class inheritance with an example.
What is difference between Private and Static Constructor?
Private Constructor - This is the constructor whose access modifier is 

private. private constructor is used to prevent a class to be 

instantiated. But, if a class has other public constructors, then that 

can be instantiated. A class can have multiple private constructor and 

can call it by another constructor.
For example:- 
Class A
{
      int a;
      private A()
      {              
       }
       public A(int b) : A()  // Calling private constructor by another constructor.
       {
                this.a=b;
        }
}


Static

Constructor :- Static constructor is used to initialize static members 

of a class. It is called by CLR, not by creating instance of the class. 

As it is called by CLR, it is not certain when it is called. But it is 

called when class is loaded. It can not be explicitly called by code. 

Static constructor has no any parameter. A class can have only one 

static constructor.
  1. Used to initialize the static members of a class.


  2. Can not access non-static members.


  3. Executes before the first instance of a class. We can not determine the time of execution.


  4. Executes by the CLR not by the object of a class.


  5. There are no parameterized static constructors since it is handled by the CLR not by the object.


  6. Time of execution might be at the loading of contained assembly.



Private Constructor



  1. Used to restrict a class to be instantiated and to be inherited.


  2. Used whenever a class contains only static members.
  3. 1)A static constructor is called before the first instance is created. i.e. global initializer.


    Whereas Private constructor is called after the instance of the class is created.


    2)Static constructor will be called first time when the class is referenced. Static constructor is used to initialize static members of the class.


      Static members will not be initialized either by private or public constructor.


    3)The static constructor will only be executed once.


      The private constructor will be executed each time it is called.
  4. Used to initialize the static members of a class. 
    Can not access non-static members. 
    Executes before the first instance of a class. We can not determine the time of execution. 
    Executes by the CLR not by the object of a class. 
    There are no parameterized static constructors since it is handled by the CLR not by the object. 
    Time of execution might be at the loading of contained assembly. 


    Private Constructor 

    Used to restrict a class to be instantiated and to be inherited. 
    Used whenever a class contains only static members.

As shown in the image above:
1. I have 2 classes - ClassB and ClassC
2. Both of these classes inherit from ClassA
3. Now, we have another class, ClassD which inherits from both ClassB and ClassC

So, if a method in ClassD calls a method defined in ClassA and ClassD has not overriden the invoked method. But both ClassB and ClassChave overridden the same method differently. Now, the ambiguity is, from which class does, ClassD inherit the invoked method: ClassB, orClassC?

In order not to have these problems, C# does not support multiple class inheritance.


What are the difference between interfaces and abstract classes

There are several differences between an abstract class and an interface as listed below.

1. Abstract classes can have implementations for some of its members, but the interface can't have implementation for any of its members.

2. Interfaces cannot have fields where as an abstract class can have fields.

3. An interface can inherit from another interface only and cannot inherit from an abstract class, where as an abstract class can inherit from another abstract class or another interface.

4. A class can inherit from multiple interfaces at the same time, where as a class cannot inherit from multiple classes at the same time.

5. Abstract class members can have access modifiers where as interface members cannot have access modifiers.

 When do you choose interface over an abstract class or vice versa?
A general rule of thumb is, If you have an implementation that will be the same for all the derived classes, then it is better to go for an abstract class instead of an interface. So, when you have an interface, you can move your implementation to any class that implements the interface. Where as, when you have an abstract class, you can share implementation for all derived classes in one central place, and avoid code duplication in derived classes
Virtual Keyword in C#: If you mark a method as virtual, it can be overriden in the derived class. A practical example for this would be, to have a default implementation in the base class and any derived class can override with its very own version of implementation. If you want a sample C# Program please read this article. The Draw() method is a virtual method, in the base DrawingObject class. But the same method is overriden in the derived classes (Traingle, Circle, Square) as per their respective requirements. Properties, events, and indexers can also be marked as virtual.

Private Constructors in C#: 

There are several reasons for using private constructors
1. If you want the caller of the class only to use the class but not instantiate. 
2. If you want to ensure a class can have only one instance at given time, i.e private constructors are used in implementing Singleton() design pattern.
3. If a class has several overloads of the constructor, and some of them should only be used by the other constructors and not external code. "If you have an implementation that will be the same for all the derived classes, then it is better to go for an abstract class instead of an interface."
Even if I don't have the same implementation, I can still go for abstract class by declaring the methods as abstract. Can you please emphasize more or explain a scenario where I would really prefer an interface over an abstract class.. I have been trying to find a concrete answer for this but in vain.. one of the advantages of using Interface is obviously Multiple inheritance as you have already explained..but am sure there has to be better answer to this...

Where did use delegates in your project - Part 1

Where did you use delegates in your project?
or
How did you use delegates in your project?
or
Usage of delegates in a Real Time Project?

This is a very common c sharp interview question. Delegates is one of the very important aspects to understand. Most of the interviewers ask you to explain the usage of delegates in a real time project that you have worked on. 

Delegates are extensively used by framework developers. Let us say we have a class called Employee as shown below.

Employee Class
 
Delegates Example Video - Part 1 
 
Click here for Delegates Example Video - Part 2
The Employee class has the following properties.
1. Id
2. Name
3. Experience
4. Salary

Now, I want you to write a method in the Employee class, which can be used to promote employees. The method should take a list of Employee objects as a parameter, and should print the names of all the employees who are eligible for a promotion. But the logic, based on which the employee gets promoted should not be hard coded. At times, we may promote employees based on their experience and at times we may promote them based on their salary or may be some other condition. So, the logic to promote employees should not be hard coded with in the method.

To achieve this, we can make use of delegates. So, now I would design my class as shown below. We also, created a delegate EligibleToPromote. This delegate takes Employee object as a parameter and returns a boolean. In the Employee class, we havePromoteEmpoloyee method. This method takes in a list of Employees and a Delegate of type EligibleToPromote as parameters. The method, then loops thru each employee object, and passes it to the delegate. If the delegate returns true, then them Employee is promoted, else not promoted. So, with in the method we have not hard coded any logic on how we want to promote employees.

C# Interview Questions on Delegates


Youtube video on Delegates 
 
Click here for Video on Multicast Delegates
What is a delegate?
A delegate is a type safe function pointer. Using delegates you can pass methods as parameters. To pass a method as a parameter, to a delegate, the signature of the method must match the signature of the delegate. This is why, delegates are called type safe function pointers.

What is the main use of delegates in C#?
Delegates are mainly used to define call back methods.

What do you mean by chaining delegates?
Or
What is a multicast delegate?
The capability of calling multiple methods on a single event is called as chaining delegates. Let me give you an example to understand this further.
1. Create a new asp.net web application
2. Drag and drop a button control and leave the ID as Button1. 
3. On the code behind file, add the code shown below.


When you click the Button now, both Method1 and Method2 will be executed. So, this capability of calling multiple methods on a single event is called as chaining delegates. In the example, we are using EventHandler delegate, to hook up Method1 and Method2 to the click event of the button control. Since, the EventHandler delegate is now pointing to multiple methods, it is also called as multicast delegate.

Will the following code compile?

No, the code does not compile. For the code to compile, the signature of Method1 should match the signature of SampleDelegate.

What are the advantages of using interfaces



This is the most commonly asked interview question. This interview question is being asked in almost all the dot net interviews. It is very important that we understand all the concepts of interfaces and abstract classes.

Interfaces are very powerful. If properly used, interfaces provide all the advantages as listed below. 

1. Interfaces allow us to implement polymorphic behaviour. Ofcourse, abstract classes can also be used to implement polymorphic behaviour.

2. Interfaces allow us to develop very loosely coupled systems.
3. Interfaces enable mocking for better unit testing.

4. Interfaces enables us to implement multiple class inheritance in C#.

5. Interfaces are great for implementing Inverson of Control or Dependancy Injection.

6. Interfaces enable parallel application development
When you don't want a massive hierarchical type framework we prefer interface
we are using interfaces in distributed architecture,, because for giving the reference to the client we use interfaces, which will provide the methods or functions signature .
and one more thing when we deploy any application on client system then we have three things to deploy i.e 
1. UI (exe file) that is nothing the application
2.config file
3.interface's .dll files

Advantages and disadvantages of using generics in C#


Generics Video Tutorial   
To better understand the advantages and disadvantages of generics, it is better you read the below 2 articles first.
1. Click here to read about Advantages and disadvantages of Arrays
2. Click here to read about Advantages and disadvantages of System.Collections


In Microsoft.NET version 1.0 there were collections, such as the ArrayList for working with groups of objects. An ArrayList is much like an array, except it could automatically grow and offered many convenience methods that arrays don't have. The problem with ArrayList and all the other .NET v1.0 collections is that they operate on type object. Since all objects derive from the object type, you can assign anything to an ArrayList. The problem with this is that you incur performance overhead converting value type objects to and from the object type and a single ArrayList could accidentally hold different types, which would cause a hard to find errors at runtime because you wrote code to work with one type. Generic collections fix these problems.


A generic collection is strongly typed (type safe), meaning that you can only put one type of object into it. This eliminates type mismatches at runtime. Another benefit of type safety is that performance is better with value type objects because they don't incur overhead of being converted to and from type object. With generic collections, you have the best of all worlds because they are strongly typed, like arrays, and you have the additional functionality, like ArrayList and other non-generic collections, without the problems.


It is always good to use generics rather than using ArrayList,Hashtable etc, found in System.Collections namespace. The only reason why you may want to use System.Collections is for backward compatibility.

I cannot think of any disadvantages of using generics at the moment. Please feel free to comment if you are aware of any disadvantages.

The screen shot below shows, the generics collection classes and their respective non generic counterparts.
Generics has some incompatibility with Nunits.

Limitation of generics:
In generic function we can't use relation operators.
What are the advantages and disadvantages of using collection classes present in System.Collections namespace


We will understand the advantages and disadvantages of using collection classes present in System.Collections namespace, using ArrayList collection class. The same advantages and disadvantages apply to all other collection classes like Stack, Queue and Hashtable classes.


Advantages of using ArrayList:
1. ArrayList can grow in size dynamcally. In the example below, the Numbers ArrayList initial size is set 2. But we have added 3 elements. This proves that ArrayList, and the rest of the collection classes like Stack, Queue and Hashtable can grow in size dynamically. If Numbers, was an integer array, then we would have run into Index Out of Range compiler error.




2. ArrayList provide several convinient methods to add and remove elements to the collection. You can use the Add(), Remove() etc which are very handy to add and remove elements respectively. Similarly the Stack, Queue and Hashtable classes have thier respective methods, to add or remove the elements.

Disadvantages of using ArrayList:
ArrayList and all other collection classes like stack, queue and hashtable which are present in System.Collection namespace operate on object and hence are loosely typed. The loosely typed nature of these collections make them vulnerable to runtime errors. Click here for an example on how the loosely typed nature of an ArrayList can cause runtime erros. 

Loosley typed collections can also cause performance overhead, because boxing and unboxing happens. In the example below, Numbers is an arraylist. We are stroing 10 and 20 which are integers and value types. Since, arraylist operate on object type, and object type is a 

reference type, the value 10 is boxed and converted into a reference type. The same is the case with integer 20. If we store 100 integers in the arraylist. All the 100 intgers are boxed, meaning converted into reference types and then stored in the collection.

When we try to retrieve the elements out of the collection, we covert the object type back to integer type, unboxing happens. So this unnecessary boxing and unboxing happens behind the scenes everytime we add and remove value types to the collection classes present in System.Collections namespace. This can severly affect the performance, especially if your collections are large. To solve this problem, we have generics introduced in dotnet. Click here for the advantages and disadvantages of using generics.
Arrays are strongly typed (cannot generate Type Errors at runtime ) but not resizable => Use it when you know exactly the number of elements you have.

ArrayList are resizable but loosely typed and so have performance overhead because of Boxing/ Unboxing problem and could generate mis match type errors at Runtime.

What are the advantages and disadvantages of using arrays


Advantages of using arrays:
1. Arrays are strongly typed, meaning you can only have one type of elements in the array. The strongly typed nature of arrays gives us 2 advantages. One, the performance will be much better because boxing and unboxing will not happen. Second, run time errors can be prevented because of type mis matches. Type mis matches and runtime errors are most commonly seen with collection classes like ArrayList, Queue, Stack etc, that are present in System.Collections namespace. 

In the example below, Numbers is an integer array. When we try to store a string in the integer array, a compiler error is reported stating cannot implicitly convert string to integer. This is why we call arrays are strongly typed.


In the example below
, Numbers is an ArrayList. Collections of type arraylist are loosely typed. This means any type of elements can be added to the collection. ArrayList operate on object type, which makes them loosely typed. No compiler error is reported, but when we run the application, a runtime error is reported as shown. In software development, it is always better to catch errors at compile time rather than at runtime.



Disadvantages of using arrays:
1. Arrays are fixed in size and cannot grow over time, where ArrayList in System.Collections namespace can grow dynamically.
2. Arrays are zero index based, and hence a little difficult to work with. The only way to store or retrieve elements from arrays, is to use integral index. Arrays donot provide convinient methods like Add(), Remove() etc provided by collection classes found in System.Collections or System.Collections.Generics namespaces, which are very easy to work with.
 we can only access an element on array by numeric index, while with ArrayList we also have other ways besides numeric index.

C# Interview Questions related to Interfaces.

Explain what is an Interface in C#?
An Interface in C# is created using the interface keyword. An example is shown below.

using System;
namespace Interfaces
{
interface IBankCustomer
{
void DepositMoney();
void WithdrawMoney();
}
public class Demo : IBankCustomer
{
public void DepositMoney()
{
Console.WriteLine("Deposit Money");
}

public void WithdrawMoney()
{
Console.WriteLine("Withdraw Money");
}

public static void Main()
{
Demo DemoObject = new Demo();
DemoObject.DepositMoney();
DemoObject.WithdrawMoney();
}
}
}
 
Interfaces Video   
Click here for video on Explicit Interface Implementation
In our example we created IBankCustomer interface. The interface declares 2 methods.
1. void DepositMoney();
2. void WithdrawMoney();

Notice that method declarations does not have access modifiers like public, private, etc. By default all interface members are public. It is a compile time error to use access modifiers on interface member declarations. Also notice that the interface methods have only declarations and not implementation. It is a compile time error to provide implementation for any interface member. In our example as the Demo class is inherited from the IBankCustomer interface, the Demo class has to provide the implementation for both the methods (WithdrawMoney() and DepositMoney()) that is inherited from the interface. If the class fails to provide implementation for any of the inherited interface member, a compile time error will be generated. Interfaces can consist of methods, properties, events, indexers, or any combination of those four member types. When a class or a struct inherits an interface, the class or struct must provide implementation for all of the members declared in the interface. The interface itself provides no functionality that a class or struct can inherit in the way that base class functionality can be inherited. However, if a base class implements an interface, the derived class inherits that implementation.

Can an Interface contain fields?
No, an Interface cannot contain fields.

What is the difference between class inheritance and interface inheritance?
Classes and structs can inherit from interfaces just like how classes can inherit a base class or struct. However there are 2 differences.
1. A class or a struct can inherit from more than one interface at the same time where as A class or a struct cannot inherit from more than one class at the same time. An example depicting the same is shown below.

using System;
namespace Interfaces
{
interface Interface1
{
void Interface1Method();
}
interface Interface2
{
void Interface2Method();
}
class BaseClass1
{
public void BaseClass1Method()
{
Console.WriteLine("BaseClass1 Method");
}
}
class BaseClass2
{
public void BaseClass2Method()
{
Console.WriteLine("BaseClass2 Method");
}
}

//Error : A class cannot inherit from more than one class at the same time
//class DerivedClass : BaseClass1, BaseClass2
//{
//}

//A class can inherit from more than one interface at the same time
public class Demo : Interface1, Interface2
{
public void Interface1Method()
{
Console.WriteLine("Interface1 Method");
}

public void Interface2Method()
{
Console.WriteLine("Interface2 Method");
}

public static void Main()
{
Demo DemoObject = new Demo();
DemoObject.Interface1Method();
DemoObject.Interface2Method();
}
}
}

2. When a class or struct inherits an interface, it inherits only the method names and signatures, because the interface itself contains no implementations.

Can an interface inherit from another interface?
Yes, an interface can inherit from another interface. It is possible for a class to inherit an interface multiple times, through base classes or interfaces it inherits. In this case, the class can only implement the interface one time, if it is declared as part of the new class. If the inherited interface is not declared as part of the new class, its implementation is provided by the base class that declared it. It is possible for a base class to implement interface members using virtual members; in that case, the class inheriting the interface can change the interface behavior by overriding the virtual members.

Can you create an instance of an interface?
No, you cannot create an instance of an interface.

If a class inherits an interface, what are the 2 options available for that class?
Option 1: Provide Implementation for all the members inheirted from the interface.

namespace Interfaces
{
interface Interface1
{
void Interface1Method();
}

class BaseClass1 : Interface1
{
public void Interface1Method()
{
Console.WriteLine("Interface1 Method");
}
public void BaseClass1Method()
{
Console.WriteLine("BaseClass1 Method");
}
}
}

Option 2: If the class does not wish to provide Implementation for all the members inheirted from the interface, then the class has to be marked as abstract.

namespace Interfaces
{
interface Interface1
{
void Interface1Method();
}

abstract class BaseClass1 : Interface1
{
abstract public void Interface1Method();
public void BaseClass1Method()
{
Console.WriteLine("BaseClass1 Method");
}
}
}

A class inherits from 2 interfaces and both the interfaces have the same method name as shown below. How should the class implement the drive method for both Car and Bus interface?
namespace Interfaces
{
interface Car
{
void Drive();
}
interface Bus
{
void Drive();
}

class Demo : Car,Bus
{
//How to implement the Drive() Method inherited from Bus and Car
}
}

To implement the Drive() method use the fully qualified name as shown in the example below. To call the respective interface drive method type cast the demo object to the respective interface and then call the drive method.

using System;
namespace Interfaces
{
interface Car
{
void Drive();
}
interface Bus
{
void Drive();
}

class Demo : Car,Bus
{
void Car.Drive()
{
Console.WriteLine("Drive Car");
}
void Bus.Drive()
{
Console.WriteLine("Drive Bus");
}

static void Main()
{
Demo DemoObject = new Demo();
((Car)DemoObject).Drive();
((Bus)DemoObject).Drive();
}
}
}

What do you mean by "Explicitly Implemeting an Interface". Give an example?
If a class is implementing the inherited interface member by prefixing the name of the interface, then the class is "Explicitly Implemeting an Interface member". The disadvantage of Explicitly Implemeting an Interface member is that, the class object has to be type casted to the interface type to invoke the interface member. An example is shown below.

using System;
namespace Interfaces
{
interface Car
{
void Drive();
}

class Demo : Car
{
// Explicit implementation of an interface member
void Car.Drive()
{
Console.WriteLine("Drive Car");
}

static void Main()
{
Demo DemoObject = new Demo();

//DemoObject.Drive();
// Error: Cannot call explicitly implemented interface method
// using the class object.
// Type cast the demo object to interface type Car
((Car)DemoObject).Drive();
}
}
}

2. When working with automatically generated source, code can be added to the class without having to recreate the source file. Visual Studio uses this approach when it creates Windows Forms, Web service wrapper code, and so on. You can create code that uses these classes without having to modify the file created by Visual Studio.

Is it possible to create partial structs, interfaces and methods?
Yes, it is possible to create partial structs, interfaces and methods. We can create partial structs, interfaces and methods the same way as we create partial classes.

Will the following code compile?
using System;
namespace PartialClass
{
  public partial class Student
  {
    public void Study()
    {
      Console.WriteLine("I am studying");
    }
  }
  public abstract partial class Student
  {
    public void Play()
    {
      Console.WriteLine("I am Playing");
    }
  }
  public class Demo
  {
    public static void Main()
    {
      Student StudentObject = new Student();
    }
  }
}

No, a compile time error will be generated stating "Cannot create an instance of the abstract class or interface "PartialClass.Student". This is because, if any part is declared abstract, then the whole class becomes abstract. Similarly if any part is declared sealed, then the whole class becomes sealed and if any part declares a base class, then the whole class inherits that base class.

Can you create partial delegates and enumerations?
No, you cannot create partial delegates and enumerations.

Can different parts of a partial class inherit from different interfaces?
Yes, different parts of a partial class can inherit from different interfaces. 

Can you specify nested classes as partial classes?
Yes, nested classes can be specified as partial classes even if the containing class is not partial. An example is shown below.

class ContainerClass
{
  public partial class Nested
  {
    void Test1() { }
  }
  public partial class Nested
  {
    void Test2() { }
  }
}

How do you create partial methods?
To create a partial method we create the declaration of the method in one part of the partial class and implementation in the other part of the partial class. The implementation is optional. If the implementation is not provided, then the method and all the calls to the method are removed at compile time. Therefore, any code in the partial class can freely use a partial method, even if the implementation is not supplied. No compile-time or run-time errors will result if the method is called but not implemented. In summary a partial method declaration consists of two parts. The definition, and the implementation. These may be in separate parts of a partial class, or in the same part. If there is no implementation declaration, then the compiler optimizes away both the defining declaration and all calls to the method.

The following are the points to keep in mind when creating partial methods.
1. Partial method declarations must begin partial keyword.
2. The return type of a partial method must be void.
3. Partial methods can have ref but not out parameters.
4. Partial methods are implicitly private, and therefore they cannot be virtual.
5. Partial methods cannot be extern, because the presence of the body determines whether they are defining or implementing.

What is the use of partial methods?
Partial methods can be used to customize generated code. They allow for a method name and signature to be reserved, so that generated code can call the method but the developer can decide whether to implement the method. Much like partial classes, partial methods enable code created by a code generator and code created by a human developer to work together without run-time costs.
Q:I have a class which is splitted into two partial classes.these two partial classes have same methods.what happens when we compile

Answer: At compile time all partial classes will be combined together to form a single final class. In same class we cannot have multiple methods with same name.But of course method overloading possible.I hope I have solved your question
Do all the parts of partial class need to be in one namespace

All parts must be defined within the same namespace.

All the parts must use the partial keyword.

All of the parts must be available at compile time to form the final type.

All the parts must have the same accessibility (i.e. public, private, etc.).

If any of the parts are declared abstract, then the entire type is abstract.

If any of the parts are declared sealed, then the entire type is sealed.

If any of the parts declare a base type, then all parts use that same base type. All parts that specify a base class must specify the same base class. You can omit a base class in one or more of the parts in which case the part still uses the same base class.
In ASP.NET, Why aspx.cs class is always declared partial?
in early .NET 1.0 framework the design(i,e aspx)and code behind(now called .cs) used to reside in same form which lead to confusion.so they made aspx.cs as partial so when compiled it will merge with aspx.and completes the class.which made developing applications simpler with no confusions

Nested Types in C#


What is a nested type. Give an example?
A type(class or a struct) defined inside another class or struct is called a nested type. An example is shown below. InnerClass is inside ContainerClass, Hence InnerClass is called as nested class.

using System;
namespace Nested
{
  class ContainerClass
  {
    class InnerClass
    {
      public string str = "A string variable in nested class";
    }

    public static void Main()
    {
      InnerClass nestedClassObj = new InnerClass();
      Console.WriteLine(nestedClassObj.str);
    }
  }
}

Will the following code compile?
using System;
namespace Nested
{
  class ContainerClass
  {
    class InnerClass
    {
      public string str = "A string variable in nested class";
    }
  }

  class Demo
  {
    public static void Main()
    {
      InnerClass nestedClassObj = new InnerClass();
      Console.WriteLine(nestedClassObj.str);
    }
  }
}

No, the above code will generate a compile time error stating - The type or namespace name 'InnerClass' could not be found (are you missing a using directive or an assembly reference?). This is bcos InnerClass is inside ContainerClass and does not have any access modifier. Hence inner class is like a private member inside ContainerClass. For the above code to compile and run, we should make InnerClass public and use the fully qualified name when creating the instance of the nested class as shown below.

using System;
namespace Nested
{
  class ContainerClass
  {
    public class InnerClass
    {
      public string str = "A string variable in nested class";
    }
  }

  class Demo
  {
    public static void Main()
    {
      ContainerClass.InnerClass nestedClassObj = new ContainerClass.InnerClass();
      Console.WriteLine(nestedClassObj.str);
    }
  }
}


Can the nested class access, the Containing class. Give an example?
Yes, the nested class, or inner class can access the containing or outer class as shown in the example below. Nested types can access private and protected members of the containing type, including any inherited private or protected members.

using System;
namespace Nested
{
  class ContainerClass
  {
    string OuterClassVariable = "I am an outer class variable";

    public class InnerClass
    {
      ContainerClass ContainerClassObject = new ContainerClass();
      string InnerClassVariable = "I am an Inner class variable";
      public InnerClass()
      {
        Console.WriteLine(ContainerClassObject.OuterClassVariable);
        Console.WriteLine(this.InnerClassVariable);
      }
    }
  }

  class Demo
  {
    public static void Main()
    {
      ContainerClass.InnerClass nestedClassObj = new ContainerClass.InnerClass();
    }
  }
}

What is the ouput of the following program?
using System;
namespace Nested
{
  class ContainerClass
  {
    public ContainerClass()
    {
      Console.WriteLine("I am a container class");
    }

    public class InnerClass : ContainerClass
    {
      public InnerClass()
      {
        Console.WriteLine("I am an inner class");
      }
    }
  }

  class DemoClass : ContainerClass.InnerClass
  {
    public DemoClass()
    {
      Console.WriteLine("I am a Demo class");
    }
    public static void Main()
    {
      DemoClass DC = new DemoClass();
    }
  }
}

Output:
I am a container class
I am an inner class
I am a Demo class

The above program has used the concepts of inheritance and nested classes. The ContainerClass is at the top in the inheritance chain. The nested InnerClass derives from outer ContainerClass. Finally the DemoClass derives from nested InnerClass. As all the 3 classes are related by inheritance we have the above output.

C# Interview Questions on Destructors


What is a Destructor?
A Destructor has the same name as the class with a tilde character and is used to destroy an instance of a class.

Can a class have more than 1 destructor? 
No, a class can have only 1 destructor.

Can structs in C# have destructors?
No, structs can have constructors but not destructors, only classes can have destructors.

Can you pass parameters to destructors? 
No, you cannot pass parameters to destructors. Hence, you cannot overload destructors.

Can you explicitly call a destructor?
No, you cannot explicitly call a destructor. Destructors are invoked automatically by the garbage collector.

Why is it not a good idea to use Empty destructors? 
When a class contains a destructor, an entry is created in the Finalize queue. When the destructor is called, the garbage collector is invoked to process the queue. If the destructor is empty, this just causes a needless loss of performance.

Is it possible to force garbage collector to run?
Yes, it possible to force garbage collector to run by calling the Collect() method, but this is not considered a good practice because this might create a performance over head. Usually the programmer has no control over when the garbage collector runs. The garbage collector checks for objects that are no longer being used by the application. If it considers an object eligible for destruction, it calls the destructor(if there is one) and reclaims the memory used to store the object.

Usually in .NET, the CLR takes care of memory management. Is there any need for a programmer to explicitly release memory and resources? If yes, why and how?
If the application is using expensive external resource, it is recommend to explicitly release the resource before the garbage collector runs and frees the object. We can do this by implementing the Dispose method from the IDisposable interface that performs the necessary cleanup for the object. This can considerably improve the performance of the application.

When do we generally use destructors to release resources?
If the application uses unmanaged resources such as windows, files, and network connections, we use destructors to release resources.
Yes, we can force GC to clean up the resource or memory which is still with the program by using GC.collect();Actually, using GC.Collect() does not force garbage collection to occur at that moment. It is simply a request.

Setting the vars to null and calling GC.Collect() can actually delay garbage collection because setting the vars to null is considered a use of the variable.
WHAT IS A CONSTRUCTOR..??

A constructor is a special member function whose task is to initialize the objects of it’s class. This is the first method that is run when an instance of a type is created. A constructor is invoked whenever an object of it’s associated class is created. If a class contains a constructor, then an object created by that class will be initialized automatically. We pass data to the constructor by enclosing it in the parentheses following the class name when creating an object. Constructors can never return a value, and can be overridden to provide custom intitialization functionality.
Usually, we put the initialization code in the constructor. Writing a constructor in the class is damn simple

C# Interview Questions on constructors


What is a constructor in C#?
Constructor is a class method that is executed when an object of a class is created. Constructor has the same name as the class, and usually used to initialize the data members of the new object. 

In C#, What will happen if you do not explicitly provide a constructor for a class?
If you do not provide a constructor explicitly for your class, C# will create one by default that instantiates the object and sets all the member variables to their default values.

Structs are not reference types. Can structs have constructors?
Yes, even though Structs are not reference types, structs can have constructors.

We cannot create instances of static classes. Can we have constructors for static classes?
Yes, static classes can also have constructors.

Can you prevent a class from being instantiated?
Yes, a class can be prevented from being instantiated by using a private constructor as shown in the example below.

using System;
namespace TestConsole
{
  class Program
  {
    public static void Main()
    {
      //Error cannot create instance of a class with private constructor
      SampleClass SC = new SampleClass();
    }
  }
  class SampleClass
  {
    double PI = 3.141;
    private SampleClass()
    {
    }
  }
}


Can a class or a struct have multiple constructors?
Yes, a class or a struct can have multiple constructors. Constructors in csharp can be overloaded.

Can a child class call the constructor of a base class?
Yes, a child class can call the constructor of a base class by using the base keyword as shown in the example below.

using System;
namespace TestConsole
{
  class BaseClass
  {
    public BaseClass(string str)
    {
      Console.WriteLine(str);
    }
  }

  class ChildClass : BaseClass
  {
    public ChildClass(string str): base(str)
    {
    }

    public static void Main()
    {
      ChildClass CC = new ChildClass("Calling base class constructor from child class");
    }
  }
}

If a child class instance is created, which class constructor is called first - base class or child class?
When an instance of a child class is created, the base class constructor is called before the child class constructor. An example is shown below.

using System;
namespace TestConsole
{
  class BaseClass
  {
    public BaseClass()
    {
      Console.WriteLine("I am a base class constructor");
    }
  }
  class ChildClass : BaseClass
  {
    public ChildClass()
    {
      Console.WriteLine("I am a child class constructor");
    }
    public static void Main()
    {
      ChildClass CC = new ChildClass();
    }
  }
}

Will the following code compile?
using System;
namespace TestConsole
{
  class BaseClass
  {
    public BaseClass(string str)
    {
      Console.WriteLine(str);
    }
  }
  class ChildClass : BaseClass
  {
    public ChildClass()
    {
      Console.WriteLine("I am a child class constructor");
    }
    public static void Main()
    {
      ChildClass CC = new ChildClass();
    }
  }
}

No, the above code will not compile. This is because, if a base class does not offer a default constructor, the derived class must make an explicit call to a base class constructor by using the base keyword as shown in the example below.

using System;
namespace TestConsole
{
  class BaseClass
  {
    public BaseClass(string str)
    {
      Console.WriteLine(str);
    }
  }
  class ChildClass : BaseClass
  {
    //Call the base class contructor from child class
    public ChildClass() : base("A call to base class constructor")
    {
      Console.WriteLine("I am a child class constructor");
    }
    public static void Main()
    {
      ChildClass CC = new ChildClass();
    }
  }
}

Can a class have static constructor?
Yes, a class can have static constructor. Static constructors are called automatically, immediately before any static fields are accessed, and are generally used to initialize static class members. It is called automatically before the first instance is created or any static members are referenced. Static constructors are called before instance constructors. An example is shown below.

using System;
namespace TestConsole
{
  class Program 
  {
    static int I;
    static Program()
    {
      I = 100;
      Console.WriteLine("Static Constructor called");
    }
    public Program()
    {
      Console.WriteLine("Instance Constructor called");
    }
    public static void Main()
    {
      Program P = new Program();
    }
  }
}

Can you mark static constructor with access modifiers?
No, we cannot use access modifiers on static constructor.

Can you have parameters for static constructors?
No, static constructors cannot have parameters.

What happens if a static constructor throws an exception?
If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.

Give 2 scenarios where static constructors can be used?
1. A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
2. Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.
if u make obj of child class then firstly your child class constructor called but this child class constr.in turn call its base class constructor(by default default constructor)
because in child class obj base class obj is initialize first and then child clas obj will created this is the reason why base class obj does not have child members because obj give you all what it contain not from outside

C# Interview Questions on Methods / Functions

  
Click here for video tutorial on Different Types of Method Parameters
Is the following code legal?
using System;
namespace Demo
{
 class Program
 {
  public static void Main()
  {

  }
  public void Sum(int FirstNumber, int SecondNumber)
  {
   int Result = FirstNumber + SecondNumber;
  }

  public int Sum(int FirstNumber, int SecondNumber)
  {
   int Result = FirstNumber + SecondNumber;
  }
 }
}

No, The above code does not compile. You cannot overload a method based on the return type. To overload a method in C# either the number or type of parameters should be different. In general the return type of a method is not part of the signature of the method for the purposes of method overloading. However, it is part of the signature of the method when determining the compatibility between a delegate and the method that it points to.

What is the difference between method parameters and method arguments. Give an example?
In the example below FirstNumber and SecondNumber are method parameters where as FN and LN are method arguments. The method definition specifies the names and types of any parameters that are required. When calling code calls the method, it provides concrete values called arguments for each parameter. The arguments must be compatible with the parameter type but the argument name (if any) used in the calling code does not have to be the same as the parameter named defined in the method.

using System;
namespace Demo
{
 class Program
 {
  public static void Main()
  {
   int FN = 10;
   int SN = 20;
   //FN and LN are method arguments
   int Total = Sum(FN, SN);
   Console.WriteLine(Total);
  }
  //FirstNumber and SecondNumber are method parameters
  public static int Sum(int FirstNumber, int SecondNumber)
  {
   int Result = FirstNumber + SecondNumber;
   return Result;
  }
 }
}


Explain the difference between passing parameters by value and passing parameters by reference with an example?
We can pass parameters to a method by value or by reference. By default all value types are passed by value where as all reference types are passed by reference. By default, when a value type is passed to a method, a copy is passed instead of the object itself. Therefore, changes to the argument have no effect on the original copy in the calling method.An example is shown below.

using System;
namespace Demo
{
 class Program
 {
  public static void Main()
  {
   int I = 10;
   int K = Function(I);

   Console.WriteLine("I = " + I);
   Console.WriteLine("K = " + K);
  }
  public static int Function(int Number)
  {
   int ChangedValue = Number + 1;
   return ChangedValue;
  }
 }
}

By default, reference types are passed by reference. When an object of a reference type is passed to a method, the reference points to the original object, not a copy of the object. Changes made through this reference will therefore be reflected in the calling method. Reference types are created by using the class keyword as shown in the example below.

using System;
namespace Demo
{
 class Program
 {
  public static void Main()
  {
   ReferenceTypeExample Object = new ReferenceTypeExample();
   Object.Number = 20;
   Console.WriteLine("Original Object Value = " + Object.Number);
   Function(Object);
   Console.WriteLine("Object Value after passed to the method= " + Object.Number);
  }
  public static void Function(ReferenceTypeExample ReferenceTypeObject)
  {
   ReferenceTypeObject.Number = ReferenceTypeObject.Number + 5;
  }
 }

 class ReferenceTypeExample
 {
  public int Number;
 }
}

Can you pass value types by reference to a method?
Yes, we can pass value types by by reference to a method. An example is shown below.

using System;
namespace Demo
{
 class Program
 {
  public static void Main()
  {
   int I = 10;
   Console.WriteLine("Value of I before passing to the method = " + I);
   Function(ref I);
   Console.WriteLine("Value of I after passing to the method by reference= " + I);
  }
  public static void Function(ref int Number)
  {
   Number = Number + 5;
  }
 }
}

If a method's return type is void, can you use a return keyword in the method?
Yes, Even though a method's return type is void, you can use the return keyword to stop the execution of the method as shown in the example below.
using System;
namespace Demo
{
 class Program
 {
  public static void Main()
  {
   SayHi();
  }
  public static void SayHi()
  {
   Console.WriteLine("Hi");
   return;
   Console.WriteLine("This statement will never be executed");
  }
 }
}
Q:What is the difference between static class and class with static methods? In which case I should use either of them?
A: If your class has only static members you never need an instance of that class so you should make the class itself static but if your class has instance members (non static) then you have to make your class an instance class to access its instance members via instances of your clas
Explicit conversion can lead to data loss where as with implicit conversions there is no data loss.

What type of data type conversion happens when the compiler encounters the following code?
ChildClass CC = new ChildClass();
ParentClass PC = new ParentClass();

Implicit Conversion. For reference types, an implicit conversion always exists from a class to any one of its direct or indirect base classes or interfaces. No special syntax is necessary because a derived class always contains all the members of a base class.


Will the following code compile? 
double d = 9999.11;
int i = d;

No, the above code will not compile. Double is a larger data type than integer. An implicit conversion is not done automatically bcos there is a data loss. Hence we have to use explicit conversion as shown below.

double d = 9999.11;
int i = (int)d; //Cast double to int.

If you want to convert a base type to a derived type, what type of conversion do you use?
Explicit conversion as shown below.
//Create a new derived type.
Car C1 = new Car();
// Implicit conversion to base type is safe.
Vehicle V = C1;

// Explicit conversion is required to cast back to derived type. The code below will compile but throw an exception at run time if the right-side object is not a Car object.
Car C2 = (Car) V;

What operators can be used to cast from one reference type to another without the risk of throwing an exception? 
The is and as operators can be used to cast from one reference type to another without the risk of throwing an exception.

If casting fails what type of exception is thrown?
InvalidCastException
ChildClass CC = new ChildClass();
ParentClass PC = new Parentclass();
These two statements do not involve any conversion.

ChildClass CC = new ParentClass();
This results in Compile time error because a base class can not be converted to derived class. We need to cast explicitly as
ParentClass PC;
ChildClass CC = (ChildClass) PC;


ParentClass PC = new ChildClass();
This is an implicit conversion which involves conversion of derived class into base class.

We can use this trick to remember.
base = derived OK
derived = base NOT OK

C# Interview questions on Boxing and Unboxing

What is Boxing and Unboxing? 
Boxing - Converting a value type to reference type is called boxing. An example is shown below.
int i = 101;
object obj = (object)i; // Boxing

Unboxing - Converting a reference type to a value typpe is called unboxing. An example is shown below.
obj = 101;
i = (int)obj; // Unboxing


Is boxing an implicit conversion?
Yes, boxing happens implicitly.

Is unboxing an implicit conversion? 
No, unboxing is an explicit conversion.

What happens during the process of boxing?
Boxing is used to store value types in the garbage-collected heap. Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by this value type. Boxing a value type allocates an object instance on the heap and copies the value into the new object. Due to this boxing and unboxing can have performance impact
in int i = 101;
object obj = (object)i; it refers to the explicit(user defined) type cast where as in second condition int i= 101; 
object o = i; this is implicit type cast....actualy first 1 cud also be written like second 1 but in this case we have option but when we perform the type casting from object to any data type then we must have to define the datatype of that casting 
because in dot net there are 16 different datatypes so the compiler wud be confused when it will cast the value from object to any datatype(Like char ,double,float int Int32 Int16 etc) in this case we must explicitly cast this value.....


Further Exmple:
int i = 100;
object ob = i;// type cast from int to object
//compiler can compile the code because it knws the object is for anonymous/any datatype.......

but when

int i = ob; // this would be wrong because now compiler dont know that which datatype wud this object contain???(either float??? int??? char??? etc) so we must explicitly define the datatype here for casting this object to the require datatype like below

int i = (int)ob;

& this is called unboxing

Basic C# Interview Questions on arrays

What is an array? 
An array is a data structure that contains several variables of the same type.

What are the 3 different types of arrays?
1.
 Single-Dimensional
2. Multidimensional
3. Jagged   

What is Jagged Array? 
A jagged array is an array of arrays.

Are arrays value types or reference types?
Arrays are reference types.

What is the base class for Array types? 
System.Array

Can you use foreach iteration on arrays in C#?
Yes,Since array type implements IEnumerable, you can use foreach iteration on all arrays in C#. 

What is the difference between string keyword and System.String class? 

string keyword is an alias for Syste.String class. Therefore, System.String and string keyword are the same, and you can use whichever naming convention you prefer. The String class provides many methods for safely creating, manipulating, and comparing strings.

Are string objects mutable or immutable? 
String objects are immutable.

What do you mean by String objects are immutable?
String objects are immutable means, they cannot be changed after they have been created. All of the String methods and C# operators that appear to modify a string actually return the results in a new string object. In the following example, when the contents of s1 and s2 are concatenated to form a single string, the two original strings are unmodified. The += operator creates a new string that contains the combined contents. That new object is assigned to the variable s1, and the original object that was assigned to s1 is released for garbage collection because no other variable holds a reference to it.

string s1 = "First String ";
string s2 = "Second String";

// Concatenate s1 and s2. This actually creates a new
// string object and stores it in s1, releasing the
// reference to the original object.
s1 += s2;

System.Console.WriteLine(s1);
// Output: First String Second String
What will be the output of the following code? 
string str1 = "Hello ";
string str2 = s1;
str1 = str1 + "C#";
System.Console.WriteLine(s2);

The output of the above code is "Hello" and not "Hello C#". This is bcos, if you create a reference to a string, and then "modify" the original string, the reference will continue to point to the original object instead of the new object that was created when the string was modified.

What is a verbatim string literal and why do we use it? 
The "@" symbol is the verbatim string literal. Use verbatim strings for convenience and better readability when the string text contains backslash characters, for example in file paths. Because verbatim strings preserve new line characters as part of the string text, they can be used to initialize multiline strings. Use double quotation marks to embed a quotation mark inside a verbatim string. The following example shows some common uses for verbatim strings:

string ImagePath = @"C:\Images\Buttons\SaveButton.jpg";
//Output: C:\Images\Buttons\SaveButton.jpg

string MultiLineText = @"This is multiline
Text written to be in
three lines.";
/* Output:
This is multiline
Text written to be in
three lines.
*/

string DoubleQuotesString = @"My Name is ""Venkat.""";
//Output: My Name is "Venkat."

More C# interview questions on strings



Will the following code compile and run? 
string str = null;
Console.WriteLine(str.Length);
The above code will compile, but at runtime System.NullReferenceException will be thrown.

How do you create empty strings in C#? 
Using string.empty as shown in the example below.
string EmptyString = string.empty;

What is the difference between System.Text.StringBuilder and System.String?
1.
 Objects of type StringBuilder are mutable where as objects of type System.String are immutable. 
2. As StringBuilder objects are mutable, they offer better performance than string objects of type System.String.
3. StringBuilder class is present in System.Text namespace where String class is present in System namespace.

How do you determine whether a String represents a numeric value?
To determine whether a String represents a numeric value use TryParse method as shown in the example below. If the string contains nonnumeric characters or the numeric value is too large or too small for the particular type you have specified, TryParse returns false and sets the out parameter to zero. Otherwise, it returns true and sets the out parameter to the numeric value of the string.

string str = "One";
int i = 0;
if(int.TryParse(str,out i))
{
     Console.WriteLine("Yes string contains Integer and it is " + i);
}
else
{
     Console.WriteLine("string does not contain Integer");
}

What is the difference between int.Parse and int.TryParse methods? 

Parse method throws an exception if the string you are trying to parse is not a valid number where as TryParse returns false and does not throw an exception if parsing fails. Hence TryParse is more efficient than Parse.

No comments:

Post a Comment