Skip Navigation LinksHome > Interview Question

Q: What is difference in between reference type and Value Type in C#?

Reference Type:
• String, object data type and user defined class, interface, & delegate. User normally creates its own type using the class, interface, and delegate.

• Reference types are created on the managed heap. Creation and removal from the managed heap is done by GC (Garbage collector).

• Reference Type are derived from System.Object.
NOTE: in .NET all the types are derived by System.Object, so all types should be Reference type. But something we all miss is that Value types are further derived from System.ValueType that makes them value type.

o A reference Type can be of null.

o Assigning one reference type to another reference type is just a copy of the reference. So both variable shares the same object in the memory. No other object is created.

o You can create the default constructor without any parameter to initialize the object.


Value Type:
• Built-in data types(except string, and object) or a user defined structure are value type such as int, long, double etc. User can create its own value type using struct.

• A value type stores its contents in memory allocated on the stack. As any value type variable goes out of the scope it is removed from the stack.

• Value types are derived System.ValueType.

• A value type cannot contain the null value except nullable type.

• Assigning one value type variable to another copies the contained value.

• Each value type has an implicit default constructor that initializes the default value of that type. You can not create the default constructor.


Q: Is multiple inheritance is allowed in C#?

No, multiple interference is allowed in C#. Only interface can be multiple times inherited.


Q: By which class all the Types are derived in C#?

No, multiple interference is allowed in C#. Only interface can be multiple times inherited.


Q: What is the difference between System.String and System.Text.StringBuilder classes?

System.String is immutable. It means any change in the string creates the new instance of the string. Due to this reason it degrades the performance of the application if we have to change more than 4 times the value of the string.

System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed. It is provide the better performance in case we have to change the value of the string more than 4 times.


Q: Can you store multiple data types in System.Array?

If array is created of built in type such as int, long, double etc than you can not store different data type values into the Array.

But if array is of type System.Object, you can store any data type including the user define data type. But there would be boxing and un-boxing involved which can degrade the performance of the application. There is no type checking so programmer has to take care of the type casting also. Wrong type casting can generate Invalid cast exception, which in deed would make application less reliable also.


Q: Can you store multiple data types in System.Array?

If array is created of built in type such as int, long, double etc than you can not store different data type values into the Array.

But if array is of type System.Object, you can store any data type including the user define data type. But there would be boxing and un-boxing involved which can degrade the performance of the application. There is no type checking so programmer has to take care of the type casting also. Wrong type casting can generate Invalid cast exception, which in deed would make application less reliable also.


Q: What is boxing and unboxing?

Boxing is name given to the process whereby a value type is converted into a reference type.
When you box a variable, you are creating a reference variable that points to a new copy on the heap. The reference variable is an object, and therefore can use all the methods that every object inherits, such as, ToString(). This is what happens in the following code:

int i = 67;                              // i is a value type
object o = i;                            // i is boxed
System.Console.WriteLine(i.ToString());  // i is boxed

unboxing is the name given to the process where by a reference type is converted to a value type. e.g. using an ArrayList to store integers. When you store an integer in the ArrayList, it's boxed. When you retrieve an integer, it must be unboxed.

ArrayList list =     New .ArrayList();  // list is a reference type
int n = 67;                              // n is a value type
list.Add(n);                             // n is boxed
n = (int)list[0];                        // list[0] is unboxed


Q: What are the public methods of System.Object?

Equals(object obj)
GetHashCode()
GetType()
ToString()


Q: What is the difference in between == operator and Equals(object obj) method?

== Operator is used to evaluate the value of two value types. If both value are equal than true otherwise false.
If we would use Equals method on value type variable it would still works fine because it would compare the value of the objects. But boxing and unboxing might happen.
 

But Equals (object obj) is used to compare two reference variable contains the same value or not.
If we would use == operator on the reference type variable it would be true only if both variable are referencing to the same object otherwise it would be false. So two different reference objects containing the same value would return false with == operator.

In case of the string == operator works perfectly fine. I would explain the reason of it in some other question.


Q: What is 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 and by default all the public. In abstract class programmer can use any access modifier for its member.

· Interface cannot have any variables, where as abstract class can have.

· Relationship with the concrete class to interface is implementing. Where as in abstract class is “is” relationship.


Q: What’s a delegate?

Delegate is reference to a method.


Q: What’s the difference between // comments, /* */ comments and /// comments?

// is Single-line, /* */ is multi-line and /// is XML documentation comments.


Q: How do you generate documentation from the C# file commented properly with a command-line compiler?

Compile it with a /doc switch.


Q: What does assert() do?

In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.


Q: What’s the difference between the Debug class and Trace class?

Use Debug class for debug builds, use Trace class for both debug and release builds.


Q: What is the difference in between standard collections and generic collections?

Generic collections are type safe and efficient, where as non generic (standard) collections are not type safe and not efficient as generics one.

It is recommended that all applications that target Version 2.0 or above use the new generic collection collections instead of the older non-generic counterparts such as ArrayList.


Q: What is Indexer?

Indexers allow instances of a class or struct to be indexed just like arrays.
Indexers resemble properties except that their accessors take parameters.
class Sampleclass
{
    private string arr = new string[100];

    public string this[int i]  //defined indexers
    {
        get
        {
            return arr[i];
        }
        set
        {
            arr[i] = value;
        }
    }
}

// This class shows how client code uses the indexer
class Program
{
    static void Main(string[] args)
    {
        Sampleclass   stringsamples = new Sampleclass();
        stringsamples [0] = "Hello, World"; //used indexer
        System.Console.WriteLine(stringsamples [0]);
    }
}

• Indexers enable objects to be indexed in a similar manner to arrays.
• A get accessor returns a value. A set accessor assigns a value.
• The this keyword is used to define the indexers.
• The value keyword is used to define the value being assigned by the set indexer.
• Indexers do not have to be indexed by an integer value; it is up to you how to define the specific look-up mechanism.
• Indexers can be overloaded.
• Indexers can have more than one formal parameter, for example, when accessing a two-dimensional array.


Q: Can more than one catch block be executed?

No. Only one catch block can be executed when any exception occurred. Catch block is traverse from top to down and first near matched exception block would be executed.


Q: If I have a return statement in the try block, finally block would be executed?

No matter what finally block would be executed. It does not matter any exception happen or nor, or any return from the try block.


Q: What is the syntax to inherit from a class in C#?

class NewClass : BaseClass
{
}


Q: How do you prevent your class from being inherited by another class?

The keyword “sealed” will prevent the class from being inherited.

public sealed class D
{
    // Class members here.
}


Q: how can you allow a class to be inherited, but prevent the method from being over-ridden?

Just leave the class public and make only the method sealed.


Q: What’s an abstract class?

A class that cannot be instantiated.  An abstract class is a class that must be inherited and have the methods overridden.  An abstract class is essentially a blueprint for a class without any implementation.


Q: What is an interface?

An interface has no implementation. It only has the signature or in other words, just the definition of the methods without the body.

They are implemented by classes/structs, and defined as separate entities from classes/structs.


Q: What is the access modifier for the members of an interface?

programmer does use any access modifier for the members of an interface. By default all the members are public. When we implement the interface, we have to use public access modifier for all the members.


Q: What happens if you inherit multiple interfaces and they have same 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 if both interface expect different functionality for the same method, but as far as compiler cares you’re okay.

e.g.
1.

interface IControl
{
    void Paint();
}
interface ISurface
{
    void Paint();
}
class SampleClass : IControl, ISurface
{
    // Both ISurface.Paint and IControl.Paint call this method.
    public void Paint()
    {
    }
}

2.

If the two interface members do not perform the same function, however, this can lead to an incorrect implementation of one or both of the interfaces.
It is possible to implement an interface member explicitly—creating a class member that is only called through the interface, and is specific to that interface. This is accomplished by naming the class member with the name of the interface and a period.
//explicit interface implementation
public class SampleClass : IControl, ISurface
{
    void IControl.Paint()
    {
        System.Console.WriteLine("IControl.Paint");
    }
    void ISurface.Paint()
    {
        System.Console.WriteLine("ISurface.Paint");
    }
}


Q: What is the difference between a Struct and a Class?

Structs are value-type variables and are thus created on the stack.
structs can not have paramter less constructor.
structs cannot inherit.

classes are reference type, created on managed heap, can have parameter less constructor, and can be inherited.


Q: What are the access modifiers in C#?

Class or struct members can be declared with one of five types of access:

private: The private keyword is a member access modifier. Private access is the least permissive access level. Private members are accessible only within the body of the class or the struct in which they are declared.

protected: The protected keyword is a member access modifier. A protected member is accessible within its class and by derived classes.

public: The public keyword is an access modifier for types and type members. Public access is the most permissive access level. There are no restrictions on accessing public members.

internal: The internal keyword is an access modifier for types and type members. Internal types or members are accessible only within files in the same assembly.

protectedinternal: Access is limited to the current assembly or types derived from the containing class.


Q: Why should use Exception in C#?

mechanism called exceptions. Exceptions are thrown by code that encounters an error and caught by code that can correct the error. Exceptions can be thrown by the .NET Framework common language runtime (CLR) or by code in a program. Once an exception is thrown, it propagates up the call stack until a catch statement for the exception is found.

After an exception is thrown, the runtime checks the current statement to see whether it is within a try block. If it is, any catch blocks associated with the try block are checked to see whether they can catch the exception. Catch blocks typically specify exception types; if the type of the catch block is the same type as the exception, or a base class of the exception, the catch block can handle the method.


Q: What is the finally block?

A finally block enables clean-up of actions performed in a try block. If present, the finally block executes after the try and catch blocks execute. A finally block is always executed, regardless of whether an exception is thrown or whether a catch block matching the exception type is found.
The finally block can be used to release resources such as file streams, database connections, and graphics handles without waiting for the garbage collector in the runtime to finalize the objects.


Q: How do you throw the exception?

Using the throw keywod.


Q: What is non-CLS exceptions and how to handle in C#?

Some .NET languages, including C++/CLI, allow objects to throw exceptions that do not derive from Exception. Such exceptions are called non-CLS exceptions or non-Exceptions. In Visual C# you cannot throw non-CLS exceptions, but you can catch them in two ways:
• Within a catch (Exception e) block as a RuntimeWrappedException.
By default, a Visual C# assembly catches non-CLS exceptions as wrapped exceptions. Use this method if you need access to the original exception, which can be accessed through the WrappedException property. The procedure later in this topic explains how to catch exceptions in this manner.
• Within a general catch block (a catch block without an exception type specified) that is put after a catch (Exception) or catch (Exception e) block.
Use this method when you want to perform some action (such as writing to a log file) in response to non-CLS exceptions, and you do not need access to the exception information. By default the common language runtime wraps all exceptions. To disable this behavior, add this assembly-level attribute to your code, typically in the AssemblyInfo.cs file: [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = false)].

// Class library written in C++/CLR.
   ThrowNonCLS.Class1 myClass = new ThrowNonCLS.Class1();

//C# code
   try
   {
    // throws gcnew System::String("I do not derive from System.Exception!");
    myClass.TestThrow();
   }
  

   catch (Exception e)
   {
    RuntimeWrappedException rwe = e as RuntimeWrappedException;
    if (rwe != null)   
    {
      String s = rwe.WrappedException as String;
      if (s != null)
      {
        Console.WriteLine(s);
      }
    }
    else
    {
       // Handle other System.Exception types.
    }
   }


Q: What is implicitly Typed Local Variables introduced in C# 3.0?

var keyword is used to declare the implicitly Typed variables. This type of variable can be only local variable so we say Implicitly Typed Local Variable.
The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement. The inferred type may be a built-in type, an anonymous type, a user-defined type, a type defined in the .NET Framework class library, or any expression.


Q: What’s the implicit name of the parameter that gets passed into the set property of a class?

Value.  The data type of the value parameter is defined by whatever data type the property is declared as.


Q: What does the keyword “virtual” declare for a method or property?

The method or property can be overridden in the derived class.


Q: How is method overriding different from method overloading?

When overriding a method, you change the behavior of the method for the derived class with same signature of the method.  Overloading a method simply involves having another method with the same name within the same class or in derived class.


Q: 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)


Q: What are the different ways a method can be overloaded?

Different parameter data types, different number of parameters, different order of parameters.


Q: 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.


Q: What is the difference in between readonly and const variables?

The readonly keyword is different from the const keyword. A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. Also, while a const field is a compile-time constant, the readonly field can be used for runtime constants.


Q: What is static constructor?

A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.


Q: How can you pass different number of parameter to a method?

The params keyword lets you specify a method parameter that takes an argument where the number of arguments is variable.
No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is permitted in a method declaration


Q: What is the difference in between typeof and GetType()?

typeof operates on a type whereas GetType operates on an object. The main point to watch out for is that GetType returns the underlying type of the object, which may not be the same as the type of the reference to the object. For example:
    class Base { }
    class Derived : Base { }

    class Program
    {
        static void Main()
        {
            ShowType( new Derived() );
        }

        static void ShowType( Base b )
        {
            Console.WriteLine(typeof(Base));
            Console.WriteLine(b.GetType());
        }
    }
gives the following output:
    Base
    Derived


Q: What is the partial method in C#?

A partial method has its signature defined in one part of a partial type, and its implementation defined in another part of the type. Partial methods enable class designers to provide method hooks, similar to event handlers, that developers may decide to implement or not. If the developer does not supply an implementation, the compiler removes the signature at compile time. The following conditions apply to partial methods:
• Signatures in both parts of the partial type must match.
• The method must return void.
• No modifiers or attributes are allowed.

    partial class A
    {
        partial void OnSomethingHappened(string s);
    }

    // This part can be in a separate file.
    partial class A
    {
        // Comment out this method and the program
        // will still compile.
        partial void OnSomethingHappened(String s)
        {
            Console.WriteLine("Something happened: {0}", s);
        }
    }


Q: What is the partial type?

Partial type definitions allow for the definition of a class, struct, or interface to be split into multiple files.
e.g.
In File1.cs:
namespace PC
{
    partial class A { }
}
 

In File2.cs:
namespace PC
{
    partial class A { }
}


Q: Can you create Windows Service Using WPF?

No, you can not build the windows Services using WPF. WPF is presentation technolgy, where as Windows service requires certain permission to perform the certain GUI retalted operations.
If the Windows service does not have the appropriate permissions, there may be unexpected results.


Q: What are the methods which can be overloaded in System.Object class?

1. Equal
2. GetHashCode
3. ToString
4. Finalize.

But if you are overloading the Equal method, then you have to overload the GetHashCode method also.

Q: test

test
User Login
Username :
Password :
Register Login

Forgot Password


Technologies