C# Basics Interview Questions and Answers

C# Basics Interview Questions and Answers

1 What is C#?
C# is a programming language designed by Microsoft. It is loosely based on C/C++, and bears a striking similarity to Java. Microsoft describe C# as follows:

“C# is a simple, modern, object oriented, and type-safe programming language derived from C and C++. C# (pronounced ‘C sharp’) is firmly planted in the C and C++ family tree of languages, and will immediately be familiar to C and C++ programmers. C# aims to combine the high productivity of Visual Basic and the raw power of C++.”
You can get the ECMA C# spec in PDF form here, or use Jon Jagger’s html version.

2 How do I develop C# apps?
The (free) .NET SDK contains the C# command-line compiler (csc.exe). Visual Studio has fully integrated support for C# development. On Linux you can use Mono.

3 Does C# replace C++?
There are three options open to the Windows developer from a C++ background:
• Stick with standard C++. Don’t use .NET at all.
• Use C++ with .NET. Microsoft supply a .NET C++ compiler that produces IL rather than machine code. However to make full use of the .NET environment (e.g. garbage collection), a set of extensions are required to standard C++. In .NET 1.x this extended language is called Managed Extensions for C++. In .NET 2.0 ME C++ has been completely redesigned under the stewardship of Stan Lippman, and renamed C++/CLI.

• Forget C++ and use C#.
Each of these options has merits, depending on the developer and the application. For my own part, I intend to use C# where possible, falling back to C++ only where necessary. ME C++ (soon to be C++/CLI) is very useful for interop between new .NET code and old C++ code – simply write a managed wrapper class using ME C++, then use the managed class from C#. From experience, this works well.

4 Does C# have its own class library?
Not exactly. The .NET Framework has a comprehensive class library, which C# can make use of. C# does not have its own class library.

5 What standard types does C# use?
C# supports a very similar range of basic types to C++, including int, long, float, double, char, string, arrays, structs and classes. However, don’t assume too much. The names may be familiar, but many of the details are different. For example, a long is 64 bits in C#, whereas in C++ the size of a long depends on the platform (typically 32 bits on a 32-bit platform, 64 bits on a 64-bit platform). Also classes and structs are almost the same in C++ – this is not true for C#. Finally, chars and strings in .NET are 16-bit (Unicode/UTF-16), not 8-bit like C++.

6. Is it true that all C# types derive from a common base class?
Yes and no. All types can be treated as if they derive from object (System.Object), but in order to treat an instance of a value type (e.g. int, float) as object-derived, the instance must be converted to a reference type using a process called ‘boxing’. In theory a developer can forget about this and let the run-time worry about when the conversion is necessary, but in reality this implicit conversion can have side-effects that may trip up the unwary.

7. So I can pass an instance of a value type to a method that takes an object as a parameter?
Yes. For example:

class CApplication
{  public static void Main()
{    int x = 25;
string s = “fred”;
DisplayMe( x );
DisplayMe( s );
static void DisplayMe( object o )
{         System.Console.WriteLine( “You are {0}”, o );

This would display:
You are 25
You are fred

8. What are the fundamental differences between value types and reference types?
C# divides types into two categories – value types and reference types. Most of the intrinsic types (e.g. int, char) are value types. Structs are also value types. Reference types include classes, arrays and strings. The basic idea is straightforward – an instance of a value type represents the actual data, whereas an instance of a reference type represents a pointer or reference to the data.

The most confusing aspect of this for C++ developers is that C# has predetermined which types are represented as values, and which are represented as references. A C++ developer expects to take responsibility for this decision.

For example, in C++ we can do this:
int x1 = 3; // x1 is a value on the stack
int *x2 = new int(3) // x2 is a pointer to a value on the heap
but in C# there is no control:
int x2 = new int();
x2 = 3; // x2 is also a value on the stack!

9. Okay, so an int is a value type, and a class is a reference type. How can int be derived from object?
It isn’t, really. When an int is being used as an int, it is a value. However, when it is being used as an object, it is a reference to an integer value (on the managed heap). In other words, when you treat an int as an object, the runtime automatically converts the int value to an object reference. This process is called boxing. The conversion involves copying the int to the heap, and creating an object instance which refers to it. Unboxing is the reverse process – the object is converted back to a value.
int x = 3; // new int value 3 on the stack
object objx = x; // new int on heap, set to value 3 – still have x=3 on stack
int y = (int)objx; // new value 3 on stack, still got x=3 on stack and objx=3 on heap

10. Are C# references the same as C++ references?
Not quite. The basic idea is the same, but one significant difference is that C# references can be null . So you cannot rely on a C# reference pointing to a valid object. In that respect a C# reference is more like a C++ pointer than a C++ reference. If you try to use a null reference, a NullReferenceException is thrown.
For example, look at the following method:

void displayStringLength( string s )
Console.WriteLine( “String is length {0}”, s.Length );

The problem with this method is that it will throw a NullReferenceException if called like this:

string s = null;
displayStringLength( s );

Of course for some situations you may deem a
NullReferenceException to be a perfectly
acceptable outcome, but in this case it might
be better to re-write the method like this:

void displayStringLength( string s )
if( s == null )
Console.WriteLine( “String is null” );

What are Namespaces?
A) Naming convention used in .Net
B) Group of classes categorized to avoid name clash
C) None of the above


What are Indexers? What is the use of it, and when to use it
An indexer is a member that enables an object to be indexed in the same way as an array. There are times when it is desirable to access a collection within a class as though the class itself were an array. For example, suppose you create a list box control named myListBox that contains alist of strings stored in a one-dimensional array, a private member variable named myStrings. Alist box control contains member properties and methods in addition to its array of strings.However, it would be convenient to be able to access the list box array with an index, just as if thelist box were an array. This can be achieved using the Indexer

What is difference between dispose() & finalize()
If you want to delete resources(objects) those are not using ,you should not worry about that, garbage collecter implicitly call finalize() method and remove all such object but if you want to delete object forcefully.The larger object ,you want to delete after completeing task),than you can explicitly call dispose() method.
Design Pattern : If your classes use unmanaged resources, you need to implement both Dispose & Finalize. Dispose() is called by user code, that is, the code that is using your class.
Finalize/Destructor cannot be called by User code, it’s called by Garbage Collector
Finalize : Is a destructor, called by Garbage Collector when the object goes out of scope. Implement it when you have unmanaged resources in your code, and want to make sure that these resources are freed when the Garbage collection happens.
Dispose : Same purpose as finalize, to free unmanaged resources. However, implement this when you are writing a custom class, that will be used by other users. Overriding Dispose() provides a way for the user code to free the unmanaged objects in your custom class.

As an aside, here’s how the GC works:



In which scenerio we use interfaces, abstract and concrete class? Which one is better and appropriate? Differentiate these three terms in depth.

The decision tree for this is pretty detailed. :) In most cases, using an abstract class is the “right” thing to do if you’re trying to create a common class from which others will derive and which isn’t fully specified. Interfaces are nice if you don’t want to force classes to have a single root class in their hierarchy, as a single class can implement multiple interfaces. Concrete classes should be used if it’s fully specified–i.e. subclasses don’t have any hooks into which they must provide functionality.
Interface – used to define a skeleton. Classes who want to confirm to that skeleton implementsts the interface
Abstract class – Use abstract class when you want to provide some functionality to the user and at the same time would like to enforce some skeleton (structure) for the users of your class
Concrete class – Use a concrete class to represent an object (data & methods) which can be extended or reused.
Use following guidelines for each of the abstractions:
– If your child classes should all implement a certain group of methods/functionalities, but each of the child classes is free to provide its own implementation, then use interfaces.

For e.g., if you are implementing a class hierarchy for vehicles, implement an interface called “Vehicle”, which has properties like Colour, MaxSpeed etc., and methods like Drive(). All child classes like “Car”, “Scooter”, “AirPlane”, “SolarCar” etc. should derive from this base interface, but provide a seperate implementation of the methods and properties exposed by Vehicle.

– If you want your child classes to implement multiple, unrelated functionalities, in short multiple inheritance, use interfaces.
For e.g., if you are implementing a class called “SpaceShip”, that has to have functionalities from a “Vehicle”,
as well as that from a “UFO”, then make both “Vehicle” and “UFO” as interfaces, and then create a class “SpaceShip” that implements both “Vehicle” and “UFO”.

Abstract Classes
– When you have a requirement where your base class should provide default implementation of certain methods, whereas other methods should be open to being overridden by child classes, use abstract classes.
For e.g., again take the example of the “Vehicle” class above. If we want all classes deriving from “Vehicle” to implement the “Drive()” method in a fixed way, whereas the other methods can be overridden by child classes. In such a scenario, we implement the “Vehicle” class as an abstract class with an implementation of “Drive”, while leave the other methods / properties as abstract so they could be overridden by child classes.
– The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share. For example, a class library may define an abstract class that is used as a parameter to many of its functions, and require programmers using that library to provide their own implementation of the class by creating a derived class.

What is the difference between Abstract and Interface? Answer
In an abstract class some methods can be concrete – there can be implementation.
In an interface class, no accessibility modifiers are allowed – are public by default.
In an abstract class accessibility modifiers are allowed.

Abstract Class:
1. Abstract Class Can contain Abstract Methods and Non-Abstract Methods.
2. When a Non-Abstract Class is Inherited from an Abstract Class, the Non-Abstract Class should provide all the implementations for the inherited Abstract Method.

1. Interface is nothing but Pure Abstract Class ie Interface can contain only the function declaration.
2. All the members of the interface are Public by Default and you cannot provide any access modifiers.
3. When a class is inherited from the interface, the inherited class should provide actual implementations for the inherited members.

What is the main difference between pointer and delegate with examples?
Delegates in c# are very similar to function pointers in c++ the only difference is that delegates are type safe due to these are CLR targated under .net framework, while function pointers in c++ are not type safe.
A Delegate in c# allows to pass a method of class to object of other class.
Rules in Deligation:-
1. In order to create a Delegate a Signature(parameter) must match Signature of object.
2. Define all the methods which has the same Signature as Deligate define.
3. Create the deligate object & pass the method as a parameter to Deligate.
4. Now call the encapsulated method using deligated object.
The best example of Deligation model is ADO.NET Architecture & Event Handling in windows environment.
Simply say Delegate is a strongly typed function pointer and pointer holds reference to a variable or pointer is a variable which holds the address of another variable.

Delegate to function— is same as—- pointer to object. Delegates are function pointers. They are used when the function which needs to be called is not know at compile time. Pointers, on the other hand, are used to point to variables or object references in unsafe code.

What is managed code?Skill/Topic: Intermediate
A) Code managed ouside the IL
B) Code which can’t be managed by the IL
C) Code written in VB.NET
D) Code to be compiled by IL

D) is the correct choice. Managed code is the code written in one of 20 high level programming languages available for use with .Net framework which is compiled into IL during the first level of compilation.

Ans : (A) The managed code are the code which are managed by the CLR not by the executalble code itself.(Ref.- MCSD Training Kit Developing Web Applicaion of PHI)
A is correct ans,

Ex: vbc compiler is compile to vb.net application in to MSIL(IL) code
csc compiler is compile to c#.net application code in to MSIL code
DotNet support multiple languages , each compiler will convert MSIL(IL) Code only. after CLR execute the code in memory before taking code in CLR, JIt will compile machine understandble code.

C# Frequently Asked Interview Questions and Answers in MNCs

C# Frequently Asked Interview Questions and Answers in MNCs

1. Does C# support multiple-inheritance?


3. Are private class-level variables inherited?

4. Describe the accessibility modifier “protected internal”.


6. What does the term immutable mean?

7. What’s the difference between System.String and System.Text.StringBuilder classes?

8. What’s the advantage of using System.Text.StringBuilder over System.String?

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



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





C Sharp,C# Interview Advanced Questions

C Sharp,C# Interview Advanced Questions

Why do I get a “CS5001: does not have an entry point defined” error when compiling?
The most common problem is that you used a lowercase ‘m’ when defining the Main method. The correct way to implement the entry point is as follows:

What does the keyword virtual mean in the method definition?
The method can be over-ridden.

What optimizations does the C# compiler perform when you use the /optimize+ compiler option?
The following is a response from a developer on the C# compiler team:
We get rid of unused locals (i.e., locals that are never read, even if assigned).
We get rid of unreachable code.
We get rid of try-catch w/ an empty try.
We get rid of try-finally w/ an empty try (convert to normal code…).
We get rid of try-finally w/ an empty finally (convert to normal code…).
We optimize branches over branches:
gotoif A, lab1
goto lab2:
turns into: gotoif !A, lab2
We optimize branches to ret, branches to next instruction, and branches to branches.

How can I create a process that is running a supplied native executable (e.g., cmd.exe)?
The following code should run the executable and wait for it to exit before
continuing: using System;
using System.Diagnostics;
public class ProcessTest {
public static void Main(string[] args) {
Process p = Process.Start(args[0]);
Console.WriteLine(args[0] + ” exited.”);
Remember to add a reference to System.Diagnostics.dll when you compile.

How do I declare inout arguments in C#?
The equivalent of inout in C# is ref. , as shown in the following
example: public void MyMethod (ref String str1, out String str2)

When calling the method, it would be called like this: String s1;
String s2;
s1 = “Hello”;
MyMethod(ref s1, out s2);
Notice that you need to specify ref when declaring the function and calling it.
Is there a way of specifying which block or loop to break out of when working with nested loops?
The easiest way is to use goto: using System;

C # Frequently Asked Questions and Answers

C # Frequently Asked Questions and Answers

What’s C# ?

- No.


- No. Static indexers are not .

using System;
class main
public static void Main()
Console.WriteLine(\”In Try block\”);
Console.WriteLine(\”In Finally block\”);


How does one compare strings in C#?
using System;
public class StringTest
public static void Main(string[] args)
int i = 10;
Console.WriteLine(\”Null Object is [\" + nullObj + \"]\n\”
+ \”Real Object is [\" + realObj + \"]\n\”
+ \”i is [\" + i + \"]\n\”);
// Show string equality operators
string str1 = \”foo\”;
string str2 = \”bar\”;
string str3 = \”bar\”;
Console.WriteLine(\”{0} == {1} ? {2}\”, str1, str2, str1 == str2 );
Console.WriteLine(\”{0} == {1} ? {2}\”, str2, str3, str2 == str3 );


Null Object is []
Real Object is [StringTest]
i is [10]
foo == bar ? False
bar == bar ? True

using System;
[assembly : MyAttributeClass] class X {}

How do you mark a method obsolete?
[Obsolete] public int Foo() {…}
Note: The O in Obsolete is always capitalized.

lock(obj) { // code }

C# Technical Interview Questions,FAQs and Answers

C# Technical Interview Questions,FAQs and Answers

Is there any sample C# code for simple threading?
Some sample code follows: 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));

What is the difference between // comments, /* */ comments and /// comments?
Single-line, multi-line and XML documentation comments.

What is the difference between and XML documentation tag?
Single line code example and multiple-line code example.

Explain the three services model (three-tier application).


How do you inherit from a class in C#?
Place a colon and then the name of the base class. Notice that it is double colon in C++.

How do I port “synchronized” functions from Visual J++ to C#?
Original Visual J++ code: public synchronized void Run()
// function body
Ported C# code: class C
public void Run()
// function body
public static void Main() {}



Is it possible to have a static indexer in C#?
No. Static indexers are not allowed in C#.

Does C# support #define for defining global constants?
#define A 1
use the following C# code: class MyConstants
public const int A = 1;

Does C# support templates?

Does C# support parameterized properties?

Does C# support C type macros?
Can you store multiple data types in System.Array?



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

Can multiple catch blocks be executed?

Can you override private virtual methods?

What is a pre-requisite for connection pooling?

What is the data provider name to connect to Access database?

Make sure that the target type set in the project properties setting is set to Windows Application, and not Console Application. If you’re using the command line, compile with /target:winexe & not target:exe.

What is the wildcard character in SQL?
What is the role of the DataReader class in ADO.NET connections?

What does the This window show in the debugger?

What is an interface class?

What is a multicast delegate?

Copy Protected by Chetan's WP-CopyProtect.