Showing posts with label Csharp Interveiw Questions. Show all posts
Showing posts with label Csharp Interveiw Questions. Show all posts

Tuesday, July 7, 2009

Csharp Interveiw Questions

1. Why is it a bad idea to throw your own exceptions?
Answer :

Well, if at that point you know that an error has occurred, then why not write the proper code to handle that error instead of passing a new Exception object to the catch block? Throwing your own exceptions signifies some design flaws in the project.
2. Why can’t you specify the accessibility modifier for methods inside the interface?
Answer :

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.
3. What’s an interface class?
Answer :

It’s an abstract class with public abstract methods all of which must be implemented in the inherited classes.
4. Can you allow class to be inherited, but prevent the method from being over-ridden?
Answer :

Yes, just leave the class public and make the method sealed.
5. Can you prevent your class from being inherited and becoming a base class for some other classes?
Answer :

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.
6. Can you override private virtual methods?
Answer :

No, moreover, you cannot access private methods in inherited classes, have to be protected in the base class to allow any sort of access.
7. Can you declare the override method static while the original method is non-static?
Answer :

No, you can’t, the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override.
8. How’s method overriding different from overloading?
Answer :
When overriding, you change the method behavior for a derived class. Overloading simply involves having a method with the same name within the class.
9. Does C# support multiple inheritance?
Answer :
No, use interfaces instead.
10. Is goto statement supported in C#? How about Java?
Answer :

Gotos are supported in C# to the fullest. In Java goto is a reserved keyword that provides absolutely no functionality.
11. What happens when you encounter a continue statement inside the for loop?
Answer :

The code for the rest of the loop is ignored, the control is transferred back to the beginning of the loop.
12. What’s the difference between const and readonly?
Answer :

You can initialize readonly variables to some runtime values. Let’s say your program uses current date and time as one of the values that won’t change. This way you declare
public readonly string DateT = new DateTime().ToString().
13. What’s different about namespace declaration when comparing that to package declaration in Java?
Answer :

No semicolon. Package declarations also have to be the first thing within the file, can’t be nested, and affect all classes within the file.
14. Can you declare a C++ type destructor in C# like ~MyClass()?
Answer :

Yes, but what’s the point, since it will call Finalize(), and Finalize() has no guarantees when the memory will be cleaned up, plus, it introduces additional load on the garbage collector. The only time the finalizer should be implemented, is when you’re dealing with unmanaged code.
15. What’s different about switch statements in C#?
Answer :

No fall-throughs allowed. Unlike the C++ switch statement, C# does not support an explicit fall through from one case label to another. If you want, you can use goto a switch-case, or goto default.
case 1:
cost += 25;
break;
case 2:
cost += 25;
goto case 1;
16. What is the difference between Finalize and Dispose (Garbage collection)
Answer :

Class instances often encapsulate control over resources that are not managed by the runtime, such as window handles (HWND), database connections, and so on. Therefore, you should provide both an explicit and an implicit way to free those resources. Provide implicit control by implementing the protected Finalize Method on an object (destructor syntax in C# and the Managed Extensions for C++). The garbage collector calls this method at some point after there are no longer any valid references to the object.
In some cases, you might want to provide programmers using an object with the ability to explicitly release these external resources before the garbage collector frees the object. If an external resource is scarce or expensive, better performance can be achieved if the programmer explicitly releases resources when they are no longer being used. To provide explicit control, implement the Dispose method provided by the IDisposable Interface. The consumer of the object should call this method when it is done using the object. Dispose can be called even if other references to the object are alive.
Note that even when you provide explicit control by way of Dispose, you should provide implicit cleanup using the Finalize method. Finalize provides a backup to prevent resources from permanently leaking if the programmer fails to call Dispose.
17. Difference between type constructor and instance constructor? What is static constructor, when it will be fired? And what is its use?
Answer :

(Class constructor method is also known as type constructor or type initializer)
Instance constructor is executed when a new instance of type is created and the class constructor is executed after the type is loaded and before any one of the type members is accessed. (It will get executed only 1st time, when we call any static methods/fields in the same class.) Class constructors are used for static field initialization. Only one class constructor per type is permitted, and it cannot use the vararg (variable argument) calling convention.
A static constructor is used to initialize a class. It is called automatically to initialize the class before the first instance is created or any static members are referenced.
18. Write one code example for compile time binding and one for run time binding? What is early/late binding?
Answer :
An object is early bound when it is assigned to a variable declared to be of a specific object type. Early bound objects allow the compiler to allocate memory and perform other optimizations before an application executes.
‘ Create a variable to hold a new object.
Dim FS As FileStream
‘ Assign a new object to the variable.
FS = New FileStream(”C:\tmp.txt”, FileMode.Open)
By contrast, an object is late bound when it is assigned to a variable declared to be of type Object. Objects of this type can hold references to any object, but lack many of the advantages of early-bound objects.
Dim xlApp As Object
xlApp = CreateObject(”Excel.Application”)
19. What are Sealed Classes in C#?
Answer :
The sealed modifier is used to prevent derivation from a class. A compile-time error occurs if a sealed class is specified as the base class of another class. (A sealed class cannot also be an abstract class)
20. In which cases you use override and new base?
Answer :

Use the new modifier to explicitly hide a member inherited from a base class. To hide an inherited member, declare it in the derived class using the same name, and modify it with the new modifier.

Csharp Interveiw Questions

1. Does C# support a variable number of arguments?
Answer :

Yes, using the params keyword. The arguments are specified as a list of arguments of a specific type, e.g. int. For ultimate flexibility, the type can be object. The standard example of a method which uses this approach is System.Console.WriteLine().
2. When should I throw an exception?
Answer :

This is the subject of some debate, and is partly a matter of taste. However, it is accepted by many that exceptions should be thrown only when an ‘unexpected’ error occurs. How do you decide if an error is expected or unexpected? This is a judgement call, but a straightforward example of an expected error is failing to read from a file because the seek pointer is at the end of the file, whereas an example of an unexpected error is failing to allocate memory from the heap.
3. What types of object can I throw as exceptions?
Answer :

Only instances of the System.Exception classes, or classes derived from System.Exception. This is in sharp contrast with C++ where instances of almost any type can be thrown
4. Can I use exceptions in C#?
Answer :
Yes, in fact exceptions are the recommended error-handling mechanism in C# (and in .NET in general). Most of the .NET framework classes use exceptions to signal errors.
5. Should I make my destructor virtual?
Answer :
A C# destructor is really just an override of the System.Object Finalize method, and so is virtual by definition.
6. Can I call a virtual method from a constructor/destructor?
Answer :

Yes, but it’s generally not a good idea. The mechanics of object construction in .NET are quite different from C++, and this affects virtual method calls in constructors.
C++ constructs objects from base to derived, so when the base constructor is executing the object is effectively a base object, and virtual method calls are routed to the base class implementation. By contrast, in .NET the derived constructor is executed first, which means the object is always a derived object and virtual method calls are always routed to the derived implementation. (Note that the C# compiler inserts a call to the base class constructor at the start of the derived constructor, thus preserving standard OO semantics by creating the illusion that the base constructor is executed first.)
The same issue arises when calling virtual methods from C# destructors. A virtual method call in a base destructor will be routed to the derived implementation.
7. How do I declare a pure virtual function in C#?
Answer :
Use the abstract modifier on the method. The class must also be marked as abstract (naturally). Note that abstract methods cannot have an implementation (unlike pure virtual C++ methods).
8. Are all methods virtual in C#?
Answer :

No. Like C++, methods are non-virtual by default, but can be marked as virtual.
9. Are C# destructors the same as C++ destructors?
Answer :

No. They look the same but they are very different. The C# destructor syntax (with the familiar ~ character) is just syntactic sugar for an override of the System.Object Finalize method. This Finalize method is called by the garbage collector when it determines that an object is no longer referenced, before it frees the memory associated with the object. So far this sounds like a C++ destructor. The difference is that the garbage collector makes no guarantees about when this procedure happens. Indeed, the algorithm employed by the CLR garbage collector means that it may be a long time after the application has finished with the object. This lack of certainty is often termed ‘non-deterministic finalization’, and it means that C# destructors are not suitable for releasing scarce resources such as database connections, file handles etc.
To achieve deterministic destruction, a class must offer a method to be used for the purpose. The standard approach is for the class to implement the IDisposable interface. The user of the object must call the Dispose() method when it has finished with the object. C# offers the ‘using’ construct to make this easier.
10. Are C# constructors the same as C++ constructors?
Answer :

Very similar, but there are some significant differences. First, C# supports constructor chaining. This means one constructor can call another:
class Person
{
public Person( string name, int age ) { … }
public Person( string name ) : this( name, 0 ) {}
public Person() : this( “”, 0 ) {}
}
Another difference is that virtual method calls within a constructor are routed to the most derived implementation
Error handling is also somewhat different. If an exception occurs during construction of a C# object, the destuctor (finalizer) will still be called. This is unlike C++ where the destructor is not called if construction is not completed.
Finally, C# has static constructors. The static constructor for a class runs before the first instance of the class is created.
Also note that (like C++) some C# developers prefer the factory method pattern over constructors.
11. Structs are largely redundant in C++. Why does C# have them?
Answer :
In C++, a struct and a class are pretty much the same thing. The only difference is the default visibility level (public for structs, private for classes). However, in C# structs and classes are very different. In C#, structs are value types (instances stored directly on the stack, or inline within heap-based objects), whereas classes are reference types (instances stored on the heap, accessed indirectly via a reference). Also structs cannot inherit from structs or classes, though they can implement interfaces. Structs cannot have destructors. A C# struct is much more like a C struct than a C++ struct.
12. What are the fundamental differences between value types and reference types?
Answer :

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 x1 = 3; // x1 is a value on the stack
int x2 = new int();
x2 = 3; // x2 is also a value on the stack!
13. What standard types does C# use?
Answer :

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++.
14. Does C# have its own class library?
Answer :

Not exactly. The .NET Framework has a comprehensive class library, which C# can make use of. C# does not have its own class library.
15. How do you mark a method obsolete?
Answer :

[Obsolete] public int Foo() {…}
or
[Obsolete(\”This is a message describing why this method is obsolete\”)] public int Foo() {…}
Note: The O in Obsolete is always capitalized.
16. How does one compare strings in C#?
Answer :

In the past, you had to call .ToString() on the strings when using the == or != operators to compare the strings’ values. That will still work, but the C# compiler now automatically compares the values instead of the references when the == or != operators are used on string types. If you actually do want to compare references, it can be done as follows: if ((object) str1 == (object) str2) { … } Here’s an example showing how string compares work:
using System;
public class StringTest
{
public static void Main(string[] args)
{
Object nullObj = null; Object realObj = new StringTest();
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 );
}
}
Output:
Null Object is []
Real Object is [StringTest]
i is [10]
foo == bar ? False
bar == bar ? True
17. Is it possible to have different access modifiers on the get/set methods of a property?
Answer :

No. The access modifier on a property applies to both its get and set accessors. What you need to do if you want them to be different is make the property read-only (by only providing a get accessor) and create a private/internal set method that is separate from the property.
18. Is it possible to restrict the scope of a field/method of a class to the classes in the same namespace?
Answer :
There is no way to restrict to a namespace. Namespaces are never units of protection. But if you’re using assemblies, you can use the ‘internal’ access modifier to restrict access to only within the assembly.
19. Is there an equivalent of exit() for quitting a C# .NET application?
Answer :

Yes, you can use System.Environment.Exit(int exitCode) to exit the application or Application.Exit() if it’s a Windows Forms app.
20. What optimizations does the C# compiler perform when you use the /optimize+ compiler option?
Answer :
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 with an empty try. We get rid of try-finally with an empty try. We get rid of try-finally with an empty finally. We optimize branches over branches: gotoif A, lab1 goto lab2: lab1: turns into: gotoif !A, lab2 lab1: We optimize branches to ret, branches to next instruction, and branches to branches.
 
Locations of visitors to this page