Pages

Men

rh

7/20/2012

Basic Interview Questions on C#

What’s the top .NET class that everything is derived from?
System.Object.


What is the difference between constant and readonly in C#?
When using the
constant keyword to set a constant variable, the value needs to be set at compile time. 

The constant keyword may not be used with an object of reference type.
 
In case a reference type needs to be assigned a non-changeable value, it may be set as readonly

In C#, can we create an object of reference type using constant keyword?
No. A constant member may not be created of an object that is of reference type, because its value is decided dynamically at runtime.

What is the difference between out and ref in C#?
1) out parameters return compiler error if they are not assigned a value in the method. Not such with ref parameters.

2) out parameters need not be initialized before passing to the method, whereas ref parameters need to have an initial value before they are passed to a method.
 
Can you prevent your class from being inherited and becoming a base class for some other classes?
Yes, that is what keyword sealed in the class definition is for. The developer trying to derive from your class will get a message: cannot inherit from Sealed class Whatever BaseClassName. It is the same concept as final class in Java.

Are private class-level variables inherited?
Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited. But they are.

Is there regular expression (regex) support available to C# developers?
Yes. The .NET class libraries provide support for regular expressions. Look at the System.Text.RegularExpressions namespace.

Does C# support multiple-inheritance?
No. But you can use Interfaces.

Where is a protected class-level variable available?
It is available to any sub-class derived from base class 

Which class is at the top of .NET class hierarchy?
System.Object.
 
What does the term immutable mean?
The data value may not be changed.
 
Note: The variable value may be changed, but the original immutable data value was discarded and a new data value was created in memory.

What’s the difference between System.String and System.Text.StringBuilder classes?
System.String is immutable.
 
System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.

What’s the advantage of using System.Text.StringBuilder over System.String?
StringBuilder is more efficient in cases where there is a large amount of string manipulation. Strings are immutable, so each time a string is changed, a new instance in memory is created.

Can you store multiple data types in System.Array?
No.

What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?
The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. 

The CopyTo() method copies the elements into another existing array. Both perform a shallow copy.

A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array. 

A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identacle object.

How can you sort the elements of the array in descending order?
By calling Sort() and then Reverse() methods.

What’s the .NET collection class that allows an element to be accessed using a unique key?
HashTable.

What class is underneath the SortedList class?
A sorted HashTable.

Will the finally block get executed if an exception has not occurred?
Yes.

What’s the C# syntax to catch any possible exception?
A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}.

I was trying to use an "out int" parameter in one of my functions. How should I declare the variable that I am passing to it?
We should declare the variable as an int, but when you pass it in you must specify it as 'out', 

Example:
int i;
Methd(out i);
 
where Methd is declared as follows: 
[return-type] foo(out int o) { }

Will finally block get executed if the exception had not occurred?
Yes.

What is the C# equivalent of C++ catch (…), which was a catch-all statement for any possible exception? Does C# support try-catch-finally blocks?
Yes. Try-catch-finally blocks are supported by the C# compiler. Here's an example of a try-catch-finally block:
 
using System;
public class TryTest
   {
    static void Main()
    {
     try
     {
      Console.WriteLine("In Try block");
      throw new ArgumentException();
     }
     catch(ArgumentException n1)
     {
      Console.WriteLine("Catch Block");
     }
     finally
     {
       Console.WriteLine("Finally Block");
      }
    }
}
 
Output: In Try Block
Catch Block
Finally Block

If I return out of a try/finally in C#, does the code in the finally-clause run?
Yes. The code in the finally always runs. If you return out of the try block, or even if you do a "goto" out of the try, the finally block always runs, as shown in the following
 

Example:
using System;
class main
 {
   public static void Main()
    {
    try
     {
      Console.WriteLine("In Try block");
      return;
      }
     finally 
     { 
       Console.WriteLine("In Finally block");
     }
   }
}

Both "In Try block" and "In Finally block" will be displayed. Whether the return is in the try block or after the try-finally block, performance is not affected either way. The compiler treats it as if the return were outside the try block anyway. If it's a return without an expression (as it is above), the IL emitted is identical whether the return is inside or outside of the try. If the return has an expression, there's an extra store/load of the value of the expression (since it has to be computed within the try block).

Is there regular expression (regex) support available to C# developers?
Yes. The .NET class libraries provide support for regular expressions. Look at the documentation for the System.Text.RegularExpressions namespace.

Does C# support properties of array types?
Yes. 
Here's a simple example: using System;
class Class1
{
   private string[] MyField;
   public string[] MyProperty
   {
    get { return MyField; }
    set { MyField = value; }
   }
}
 
class MainClass
 {
    public static int Main(string[] args)
    {
     Class1 c = new Class1();
     string[] arr = new string[] {"apple", "banana"};
     c.MyProperty = arr;
     Console.WriteLine(c.MyProperty[0]); // "apple"
     return 0;
   }
}
When do you absolutely have to declare a class as abstract (as opposed to free-willed educated choice or decision based on UML diagram)?
When at least one of the methods in the class is abstract. When the class itself is inherited from an abstract class, but not all base abstract methods have been over-ridden.


My switch statement works differently than in C++! Why? 
C# does not support an explicit fall through for case blocks. The following code is not legal and will not compile in C#:
switch(x)
{
 case 0: // do something
 case 1: // do something as continuation of case 0
 default: // do something in common with
  //0, 1 and everything else
  break;
}
To achieve the same effect in C#, the code must be modified as shown below (notice how the control flows are explicit):
class Test
{
  public static void Main()
  {
   int x = 3;
   switch(x)
   {
    case 0: // do something
    goto case 1;
    case 1: // do something in common with 0
    goto default;
    default: // do something in common with 0, 1, and anything else
    break;
   }
 }
 
Is there any sample C# code for simple threading? - Yes:

using System;

using System.Threading;
class ThreadTest
{
 public void runme()
 {
   Console.WriteLine("Runme Called");
 }
 public static void Main(String[] args)
 {
  ThreadTest b = new ThreadTest();
  Thread t = new Thread(new ThreadStart(b.runme));
  t.Start();
  }

 }

}
Can multiple catch blocks be executed for a single try statement?
No. Once the proper catch block processed, control is transferred to the finally block .
What happens if you inherit multiple interfaces and they have conflicting method names?
It’s up to you to implement the method inside your own class, so implementation is left entirely up to you. This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data, but as far as compiler cares you’re okay.

What’s the implicit name of the parameter that gets passed into the set method/property of a class?
Value. The data type of the value parameter is defined by whatever data type the property is declared .

Can you declare an override method to be static if the original method is not static?
No. The signature of the virtual method must remain the same. (Note: Only the keyword virtual is changed to keyword override)

What are the different ways a method can be overloaded?
Different parameter data types, different number of parameters, different order of parameters.

If a base class has a number of overloaded constructors, and an inheriting class has a number of overloaded constructors; can you enforce a call from an inherited constructor to a specific base constructor?
Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class.

What’s a delegate?
A delegate object encapsulates a reference to a method.

What’s a multicast delegate?
A delegate that has multiple handlers assigned to it. Each assigned handler (method) is called.

What’s the implicit name of the parameter that gets passed into the class’ set method?
Value, and it’s datatype depends on whatever variable we’re changing.

How do you inherit from a class in C#?
Place a colon and then the name of the base class.

Does C# support multiple inheritance?
No, use interfaces instead.

When you inherit a protected class-level variable, who is it available to?
Classes in the same namespace.

Are private class-level variables inherited?
Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited.

How’s method overriding different from overloading?
When overriding, you change the method behavior for a derived class. Overloading simply involves having a method with the same name within the class.

What does the keyword virtual mean in the method definition?
The method can be over-ridden.
 
Can you declare the override method static while the original method is non-static?
No, you can’t, the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override.

Can you override private virtual methods?
No, moreover, you cannot access private methods in inherited classes, have to be protected in the base class to allow any sort of access.

Can you prevent your class from being inherited and becoming a base class for some other classes?
Yes, that’s what keyword sealed in the class definition is for. The developer trying to derive from your class will get a message: cannot inherit from Sealed class WhateverBaseClassName.
It’s the same concept as final class in Java.

Can you allow class to be inherited, but prevent the method from being over-ridden?
Yes, just leave the class public and make the method sealed.

What’s an abstract class?
A class that cannot be instantiated. A concept in C++ known as pure virtual method. A class that must be inherited and have the methods over-ridden.
Essentially, it’s a blueprint for a class without any implementation.

When do you absolutely have to declare a class as abstract (as opposed to free-willed educated choice or decision based on UML diagram)?

When at least one of the methods in the class is abstract. When the class itself is inherited from an abstract class, but not all base abstract methods have been over-ridden.

What’s an interface class?
It’s an abstract class with public abstract methods all of which must be implemented in the inherited classes.

Why can’t you specify the accessibility modifier for methods inside the interface?
They all must be public. Therefore, to prevent you from getting the false impression that you have any freedom of choice, you are not allowed to specify any accessibility, it’s public by default.

Can you inherit multiple interfaces?
Yes, why not.
 
And if they have conflicting method names?
It’s up to you to implement the method inside your own class, so implementation is left entirely up to you.
This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data, but as far as compiler cares you’re okay.

What’s the difference between an interface and abstract class?
In the interface all methods must be abstract, in the abstract class some methods can be concrete. In the interface no accessibility modifiers are allowed, which is ok in abstract classes.

How can you overload a method?
Different parameter data types, different number of parameters, different order of parameters.

If a base class has a bunch of overloaded constructors, and an inherited class has another bunch of overloaded constructors, can you enforce a call from an inherited constructor to an arbitrary base constructor?
Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class.

What’s the difference between System.String and System.StringBuilder classes?
System.String is immutable, System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.

Is it namespace class or class namespace?
The .NET class library is organized into namespaces. Each namespace contains a functionally related group of classes so natural namespace comes first.

What is the difference between Finalize() and Dispose()?
Dispose() is called by as an indication for an object to release any unmanaged resources it has held.
 
Finalize() is used for the same purpose as dispose however finalize doesn’t assure the garbage collection of an object.
 
Dispose() operates determinalistically due to which it is generally preferred

Explain how to add controls dynamically to the form using C#.NET.
The following code can be called on some event like page load or onload of some image or even a user action like onclick
protected void add_button(Button button)
{
try
{
panel1.Controls.Add(button); // Add the control to the container on a page
}
catch (Exception ex)
{
label1.Text += ex.Message.ToString();
}
}
What are Extender provider components? Explain how to use an extender provider in the project.
An extender provider is a component that provides properties to other components.
Implementing an extender provider:
  • Use the ProvidePropertyAttribute, which specifies the name of the property that an implementer of IExtenderProvider provides to other components, attribute to specify the property provided by your extender provider.
  • Implement the provided property.
  • Track which controls receive your provided property.
  • Implement the IExtenderProvider, which defines the interface for extending properties to other components in a containe, interface.
 What is an interface class?
An interface class is an abstract class with public abstract methods. You can inherit the class and have the methods over-ridden. 

Define Interface class in C#.NET.
It is an abstract class with public abstract methods with no implimentation.

Difference between // comments, /* */ comments and /// comments.
// comments - It is Single-line comment
/* */ comments - It is multi-line comment
/// comments - It is XML documentation comments.

How do you inherit derived class from a base class in C#.NET? Name the Top .NET class that everything is derived from.
By using colon and then the name of the base class. 

What is the implicit name of the parameter that gets passed into the class set method?
Value, and its datatype depends on whatever variable we are changing.

What is delay signing?
Delay signing allows you to place a shared assembly in the GAC by signing the assembly with just the public key. This allows the assembly to be signed with the private key at a later stage, when the development process is complete and the component or assembly is ready to be deployed. This process enables developers to work with shared assemblies as if they were strongly named, and it secures the private key of the signature from being accessed at different stages of development.

Is there an equivalent of exit() for quitting a C# .NET application?
Yes, you can use System.Environment.Exit(int exitCode) to exit the application or Application.Exit() if it's a Windows Forms app.

If a base class has a bunch of overloaded constructors, and an inherited class has another bunch of overloaded constructors, can you enforce a call from an inherited constructor to an arbitrary base constructor?
Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class

What are the different parameter modifiers available in C#?
What is a parameter modifier?
Parameter modifiers in C# are entities that controls the behaviour of the arguments passed in a method. Following are the different parameter modifiers in C#:
 
1) None - if there is NO parameter modifier with an argument, it is passed by value, where the method recieves a copy of the original data.
 
2) out - argument is passed by reference. The argument marked with "out" modifier needs to be assigned a value within this function, otherwise a compiler error is returned.
 
void multiply(int a, int b, out int prod)
{
prod = a * b;
}
Here, note that prod is assigned a value. If not done so, then a compile time error is returned.
 
3) params- This modifier gives the permission to set a variable number of identical datatype arguments.

Note that a method may have only one "params" modifier. The params modifier needs to be in the last argument.
 
static int totalruns(params int[] runs)
{
int score = 0;
for(int x=0; x
&nsbp;score+=runs[x];
return score;
}
 
Further, from the calling function, we may pass the scores of each batsman as below...
score = totalruns(12,36,0,5,83,25,26);

4) ref - The argument is given a value by the caller, where data is passed by reference. This value may optionally be reset in the called method. Note that even if NO value is set in the called method for the ref attribute, no compiler error is raised.

 
Why is the new keyword used for instantiating an object in .NET?
The new keyword instructs the .NET compiler to instantiate a new object, with appropriate number of bytes (depending on the type) for the object and gather required memory from the managed heap.

What are the default values for bool, int, double, string, char, reference-type variables?
When the objects of the following types are declared, then they have a default value during declaration. The following table shows the default value for each type:
Type Default Value
bool false
int 0
double 0
string null
char '\0'
Reference Type null

How to declare a constant variable in C#? What is the use of the const keyword?
If a variable needs to have a fixed value, that may not be changed across the application's life, then it may be declared with the const keyword. The value assigned to a constant variable (using the const keyword) must be known at the time of compilation

What is the use of GetCommandLineArgs() method?
The GetCommandLineArgs() method is used to access the command line arguments. The return value of this method is an array of strings. It is a method of the System.Environment class. See the code example below:
public static int Main(string[] args)
{
string[] strArgs = System.Environment.GetCommandLineArgs();
Console.WriteLine("Arguments {0}", strArgs[0]);
}

Can we set different types of parameters & return-types in main() method"?
Yes. The Main() method may easily be played around with by developers by passing different parameters and setting different return types. See the code below, that demonstrates different ways the Main() method may be implemented:
(1)
public static void Main(string[] args)
{
//NO return type, the argument is an array of strings
}

(2)
public static int Main(string[] args)
{
//Return type is int, argument is an array of strings
}

(3)
What is wrapper class? is it available in c#?
Wrapper Classes are the classes that wrap up the primitive values in to a class that offer utility method to access it .
For eg you can store list of int values in a vector class and access the class. Also the methods are static and hence you can use them without creating an instance . The values are immutable wrapper class are those class in which we can not define and call all predefined function .it is possible in java not C#.

Which tool is used to browse the classes, structs, interfaces etc. in the BCL?
wincv as in Windows Class View

How is the using() pattern useful? What is IDisposable? How does it support deterministic finalization?
The using() pattern is useful because it ensures that Dispose() will always be called when a disposable object (defined as one that implements IDisposable, and thus the Dispose() method) goes out of scope, even if it does so by an exception being thrown, and thus that resources are always released.

What is object pooling
Defination: A performance optimization based on using collections of pre-allocated resources, such as objects or database connections
With the advent of the .NET platform, writing code that pools objects and threads has become a simple task. By using the Threading and Collections namespaces, you can create robust object pooling applications. This could also be done by implementing COM+ interop interfaces into your code.

Which method is actually called ultimately when Console.WriteLine( ) is invoked?
A) Append( )
B) AppendFormat( )
C) Tostring( )
Ans: B, AppendFormat() method is called.

Whats the use of "throw" keyword in C#?
The throw keyword is used to throw an exception programatically in C#. In .NET, there is an in-built technique to manage & throw exceptions. In C#, there are 3 keyword, that are used to implement the Exception Handling. These are the try, catch and finally keywords. In case an exception has to be implicitly thrown, then the throw keyword is used. See code example below, for throwing an exception programatically...

class SomeClass
{
public static void Main()
{
try
{
throw new DivideByZeroException("Invalid Division Occured");
}
catch(DivideByZeroException e)
{
Console.WriteLine("Exception - Divide by Zero" );
}
}
}

Can we put multiple catch blocks in a single try statement in C#?
Yes. Multiple catch blocks may be put in a try block. See code example below, to see multiple catch blocks being used in C#.

Example:-
class ClassA
{
public static void Main()
{
int y = 0;
try
{
val = 100/y;
Console.WriteLine("Line not executed");
}
catch(DivideByZeroException ex)
{
Console.WriteLine("DivideByZeroException" );
}

catch(Exception ex)
{
Console.WritLine("Some Exception" );
}

finally
{
Console.WriteLine("This Finally Line gets executed always");
}
Console.WriteLine("Result is {0}",val);
}
}

How to achieve polymorphism in C#?
In C#, polymorphism may be achieved by overloading a function, overloading an operator, changing the order of types, changing the types using the same name for the member in context. To see some code examples of polymorphism, Click Here.

How to add a ReadOnly property in C#?
Property - A property is an entity that describes the features of an object. A property is a piece of data contained within a class that has an exposed interface for reading/writing. Looking at that definition, you might think you could declare a public variable in a class and call it a property. While this assumption is somewhat valid, the true technical term for a public variable in a class is a field.

The key difference between a field and a property is in the inclusion of an interface. We make use of Get and Set keywords while working with properties. We prefix the variables used within this code block with an underscore. Value is a keyword, that holds the value which is being retrieved or set. See code below to set a property as ReadOnly. If a property does not have a set accessor, it becomes a ReadOnly property.

Example:-
public class ClassA
{
private int length = 0;
public ClassA(int propVal)
{
length = propVal;
}
public int length
{
get
{
return length;
}
}
}

How to prevent a class from being inherited? Sealed in C#?
In order to prevent a class in C# from being inherited, the sealed keyword is used. Thus a sealed class may not serve as a base class of any other class. It is also obvious that a sealed class cannot be an abstract class. Code below...

Example:-
sealed class ClassA
{
public int x;
public int y;
}

No class can inherit from ClassA defined above. Instances of ClassA may be created and its members may then be accessed, but nothing like the code below is possible...

class DerivedClass: ClassA {} // Error

Can we inherit multiple interfaces in C#?
Yes. Multiple interfaces may be inherited in C#.

Note that when a class and multiple interfaces are to be inherited, then the class name should be written first, followed by the names of the interfaces. See code example below, on how to inherit multiple interfaces in C#.
class someclass : parentclass, IInterface1, IInterface2
{
//...Some code in C#
}

How to call a specific base constructor in C#?

What is the use of the base keyword.
Suppose we have a derived class named dotnetderivedclass. If this derived class is to invoke the constructor of a base class, we make use of the base keyword. See code example below on how to use a base keyword to invoke the base class constructor.

public class dotnetClass
{
public dotnetClass()
{
// The 1st base class constructor defined here
}

public dotnetClass(string Name)
{
// The 2nd base class constructor defined here
}
}

public class dotnetderivedclass : dotnetClass
// A class is being inherited out here
{
public dotnetderivedclass()
{
// dotnetderivedclass 1st constructor defined here
}

public dotnetderivedclass(string name):base(name)
{
// dotnetderivedclass 2nd constructor defined here
}
}

Note that we have used the base keyword in the sample code above. The sequence of execution of the constructors will be as follows:
public dotnetClass() method -> public dotnetderivedclass() method

The above sequence triggers when there is no initializer to the base class, and thus it triggers the parameterless base class constructor. The other base class constructor may also get invoked when we pass a parameter while defining it.

Can a class be created without a constructor?
No. In case we dont define the constructor, the class will access the no-argument constructor from its base class. The compiler will make this happen during compilation.

What is the use of the main() function in C#?
Every executable C# application must contain a class defining a Main() method that signifies the entry point of the application. Note that the Main() method is of the access type public by nature. Moreover, it is also static. See example below:

Example:
using System;
class Question
{
public static int Main(string[] args)
{
Console.Writeline("Another Question");
Console.Readline();
return 0;
}
}

A public member is accessible from other types. The main() method is set as static so that it may be invoked at class level itself, without the need of creating an instance of it. The single parameter is an array of strings. that may contain any number of incoming command line arguments.

Can we set the specifier of the main() method in C# as private?
Yes. When the access specifier is set as private for the Main() method, then other assemblies may not invoke this class' Main() method as the starting point of the application. The startup scope gets limited to the class in context itself. See code below:

public static int Main()
{
//Return type is int, NO arguments
}

(4)
public static void Main()
{
//Return type is void, NO arguments
}