Friday, July 24, 2009

Difference between Overriding and Overloading

Difference between Overriding and Overloading

Overriding is the example of run-time polymorphism and
Overloading is the example of compile-time polymorphism.

■The return type must exactly match that of the overridden method.
■The access level must not be more restrictive than that of the overridden method.
■The access level can be less restrictive than that of the overridden method.
■The overriding method must not throw new or broader checked exceptions than those declared by the overridden method.
■The overriding method can throw narrower or fewer exceptions. Just because an overridden method “takes risks” doesn’t mean that the overriding subclass’ exception takes the same risks. Bottom line: An overriding method doesn’t have to declare any exceptions that it will never throw, regardless of what the overridden method declares.
■You cannot override a method marked final.
■If a method can’t be inherited, you cannot override it.
Overloaded method
■Overloaded methods must change the argument list.
■Overloaded methods can change the return type.
■Overloaded methods can change the access modifier.
■Overloaded methods can declare new or broader checked exceptions.
■A method can be overloaded in the same class or in a subclass.

Friday, July 17, 2009

What is the difference between DELETE and TRUNCATE? Is one faster than the other?

DELETE logs the data for each row affected by the statement in the transaction log and physically removes the row from the file, one row at a time. The recording of each affected row can cause your transaction log grow massively if you are deleting huge numbers of rows. However, when you run your databases in full recovery mode, detailed logging is necessary for SQL Server to be able to recover the database to the most recent state, should a problem arise. The fact that each row is logged explains why DELETE statements can be slow.

TRUNCATE is faster than DELETE due to the way TRUNCATE "removes" rows. Actually, TRUNCATE does not remove data, but rather deallocates whole data pages and removes pointers to indexes. The data still exists until it is overwritten or the database is shrunk. This action does not require a lot of resources and is therefore very fast. It is a common mistake to think that TRUNCATE is not logged. This is wrong. The deallocation of the data pages is recorded in the log file. Therefore, BOL refers to TRUNCATE operations as "minimally logged" operations. You can use TRUNCATE within a transaction, and when this transaction is rolled-back, the data pages are reallocated again and the database is again in its original, consistent state.

Some limitations do exist for using TRUNCATE.

· You need to be db_owner, ddl_admin, or owner of the table to be able to fire a TRUNCATE statement.

· TRUNCATE will not work on tables, which are referenced by one or more FOREIGN KEY constraints.

So if TRUNCATE is so much faster than DELETE, should one use DELETE at all? Well, TRUNCATE is an all-or-nothing approach. You can't specify just to truncate those rows that match a certain criteria. It's either all rows or none.

You can, however, use a workaround here. Suppose you want to delete more rows from a table than will remain. In this case you can export the rows that you want to keep to a temporary table, run the TRUNCATE statement, and finally reimport the remaining rows from the temporary table. If your table contains a column with the IDENTITY property defined on it, and you want to keep the original IDENTITY values, be sure to enabled IDENTITY_INSERT on the table before you reimport from the temporary table. Chances are good that this workaround is still faster than a DELETE operation.

You can also set the recovery mode to "Simple" before you start this workaround, and then back to "Full" one it is done. However, keep in mind that is this case, you might only be able to recover to the last full backup.

Thursday, July 16, 2009

What are triggers? How to invoke a trigger on demand?

Triggers are special kind of stored procedures that get executed automatically when an INSERT, UPDATE or DELETE operation takes place on a table.

Triggers can't be invoked on demand. They get triggered only when an associated action (INSERT, UPDATE, DELETE) happens on the table on which they are defined.

Triggers are generally used to implement business rules, auditing. Triggers can also be used to extend the referential integrity checks, but wherever possible, use constraints for this purpose, instead of triggers, as constraints are much faster.

What is AJAX in ASP.Net

Ajax stands for Asynchronous Javascript & XML. It is a web technology through which a postback from a client (browser) to the server goes partially, which means that instead of a complete postback, a partial postback is triggered by the Javascript XmlHttpRequest object. In such a scenario, web-application users won't be able to view the complete postback progress bar shown by the browser. In an AJAX environment, it is Javascript that starts the communication with the web server.

Ajax technology in a website may be implemented by using plain Javascript and XML. Code in such a scenario may tend to look little complex, for which the AJAX Framework in .NET can be embedded in ASP.NET web applications.

In addition to XML & Javascript, AJAX is also based on DOM - the Document Object Model technology of browsers through which objects of the browser can be accessed through the memory heap using their address.

What is WPF in .Net

Windows Presentation Foundation (WPF) is Microsoft's development tool for Web applications and rich client applications.With WPF, developers can use XAML, the Extensible Application Markup Language, to create custom controls, graphics, 3D images and animations that are not available in traditional HTML implementations.

What is WCF in .Net 3.5

Windows Communication Foundation (WCF)
is Microsoft's programming model for using managed code to build unified Web services and other distributed systems that can talk to each other.
WCF focuses on connecting XML to programs that are built using development languages supported by Microsoft, such as VB.NET and C#.
To support this cross-language communication, WCF uses the extensible Simple Object Access Protocol (SOAP).

What is Web Services in .Net

In ASP.NET, a web service is essentially a listener that monitors a particular URL exposed via HTTP, looking for requests packaged as SOAP messages. When a request arrives, the ASP.NET runtime unpackages the request and calls the method for which the request is intended, passing in any parameters included with the request. If the request has a return value (which is not required), the ASP.NET runtime packages up the return value (based on the XML schema datatype specifications) and sends it to the client as a SOAP message. What this means to developers is that your application doesn't need to know anything about the client that will consume it, other than the fact that it can understand XML and SOAP. Thus, developers can essentially write methods that will be called as web services just as though they were writing methods that would be called locally.

This functionality is provided by the runtime largely for free. Developers expose their functionality as web services by marking their methods with a specific metadata attribute, the WebService attribute. The Common Language Runtime (CLR) takes care of the rest—from packaging and unpackaging SOAP requests to automatically providing HTML documentation of the web service—if it is called from a web browser (rather than by a SOAP request).

Monday, July 13, 2009

Advantages of Stored Procedures

Using stored procedures provides many advantages over executing large and complex SQL
batches from client applications. The following are some of them:
. Modular programming—Subroutines and functions are often used in ordinary 3GL
and 4GL languages (such as C, C++, and Microsoft Visual Basic) to break code into
smaller, more manageable pieces. The same advantages are achieved when using
stored procedures, with the difference that the stored procedure is stored in SQL
Server and can be called by any client application.
. Restricted, function-based access to tables—Someone can have access to execute a
stored procedure without having permissions to operate directly on the underlying
. Reduced network traffic—Stored procedures can consist of many individual SQL
statements but can be executed with a single statement. This allows you to reduce
the number and size of calls from the client to the server.
. Faster execution—Stored procedures’ query plans are kept in memory after the first
execution. The code doesn’t have to be reparsed and reoptimized on subsequent
. Enforced consistency—If users modify data only through stored procedures, problems
that often result from ad hoc modifications (such as omitting a crucial WHERE
clause) are eliminated.
. Reduced operator and programmer errors—Because less information is being
passed, complex tasks can be executed more easily, with less likelihood of
SQL errors.
. Automating complex or sensitive transactions—If all modifications of certain
tables take place in stored procedures, you can guarantee the data integrity on those


Stored procedures are compiled and are the fastest possible
means of executing a batch or query.

Executing the processing at the server instead of the desktop
greatly reduces network traffic.

Stored procedures offer modularity and are an easy means of deploying features and
code changes. If the front-end application calls a stored procedure to perform some
processing, modifying a stored procedure in a single location upgrades all users.

Stored procedures can be an important component in database security. If all user
access goes through stored procedures, direct access to the tables can be denied and
all access to the data can be controlled.

Tuesday, July 7, 2009

OOPS Interview Question

1. You have one base class virtual function how will call that function from derived class?
Answer :
class a
public virtual int m()
return 1;
class b:a
public int j()
return m();
2. Can we call a base class method without creating instance?
Answer :

Its possible If its a static method.
Its possible by inheriting from that class also.
Its possible from derived classes using base keyword.
3. What is Method Overriding? How to override a function in C#?
Answer :

Use the override modifier to modify a method, a property, an indexer, or an event. An override method provides a new implementation of a member inherited from a base class. The method overridden by an override declaration is known as the overridden base method. The overridden base method must have the same signature as the override method.
You cannot override a non-virtual or static method. The overridden base method must be virtual, abstract, or override
4. What’s an abstract class?
Answer :

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.
5. When do you absolutely have to declare a class as abstract?
Answer :
1. When the class itself is inherited from an abstract class, but not all base abstract methods have been overridden.
2. When at least one of the methods in the class is abstract.
6. What is an interface class?
Answer :

Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes.
7. What happens if you inherit multiple interfaces and they have conflicting method names?
Answer :
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 it is okay.
8. What’s the difference between an interface and abstract class?
Answer :

In an interface class, all methods are abstract - there is no implementation. In an abstract class some methods can be concrete. In an interface class, no accessibility modifiers are allowed. An abstract class may have accessibility modifiers.
9. How is method overriding different from method overloading?
Answer :
When overriding a method, you change the behavior of the method for the derived class. Overloading a method simply involves having another method with the same name within the class.
10. 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?
Answer :

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.
11. What are the different ways a method can be overloaded?
Answer :
Different parameter data types, different number of parameters, different order of parameters.
12. Can you prevent your class from being inherited by another class?
Answer :
Yes. The keyword “sealed” will prevent the class from being inherited.
13. What’s the C# syntax to catch any possible exception?
Answer :
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 {}
14. What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?
Answer :
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.
15. What’s the advantage of using System.Text.StringBuilder over System.String?
Answer :
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.
16. What’s the difference between System.String and System.Text.StringBuilder classes?
Answer :
System.String is immutable. System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.
17. What does the term immutable mean?
Answer :
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.
18. List out some of the exception classes in C#?
Answer :
Common Exception Classes :
The following exceptions are thrown by certain C# operations.
System.OutOfMemoryException Thrown when an attempt to allocate memory (via new) fails.
System.StackOverflowException Thrown when the execution stack is exhausted by having too many pending method calls; typically indicative of very deep or unbounded recursion.
System.NullReferenceException Thrown when a null reference is used in a way that causes the referenced object to be required.
System.TypeInitializationException Thrown when a static constructor throws an exception, and no catch clauses exists to catch in.
System.InvalidCastException Thrown when an explicit conversion from a base type or interface to a derived types fails at run time.
System.ArrayTypeMismatchException Thrown when a store into an array fails because the actual type of the stored element is incompatible with the actual type of the array.
System.IndexOutOfRangeException Thrown when an attempt to index an array via an index that is less than zero or outside the bounds of the array.
System.MulticastNotSupportedException Thrown when an attempt to combine two non-null delegates fails, because the delegate type does not have a void return type.
System.ArithmeticException A base class for exceptions that occur during arithmetic operations, such as DivideByZeroException and OverflowException.
System.DivideByZeroException Thrown when an attempt to divide an integral value by zero occurs.
System.OverflowException Thrown when an arithmetic operation in a checked context overflows.

19. Can you tell me about Array Covariance?
Answer :
For any two reference-types A and B, if an implicit reference conversion or explicit reference conversion exists from A to B, then the same reference conversion also exists from the array type A[R] to the array type B[R], where R is any given rank-specifier (but the same for both array types). This relationship is known as array covariance. Array covariance in particular means that a value of an array type A[R] may actually be a reference to an instance of an array type B[R], provided an implicit reference conversion exists from B to A.
Because of array covariance, assignments to elements of reference type arrays include a run-time check which ensures that the value being assigned to the array element is actually of a permitted type
20. What are Labeled statements?
Answer :
A labeled-statement permits a statement to be prefixed by a label. Labeled statements are permitted blocks, but are not permitted as embedded statements.
identifier : statement
A labeled statement declares a label with the name given by the identifier. The scope of a label is the block in which the label is declared, including any nested blocks. It is an error for two labels with the same name to have overlapping scopes.
A label can be referenced from goto statements within the scope of the label. This means that goto statements can transfer control inside blocks and out of blocks, but never into blocks
21. Do you Know about Versioning?
Answer :
Versioning is the process of evolving a component over time in a compatible manner. A new version of a component is source compatible with a previous version if code that depends on the previous version can, when recompiled, work with the new version. In contrast, a new version of a component is binary compatible if a program that depended on the old version can, without recompilation, work with the new version.Most languages do not support binary compatibility at all, and many do little to facilitate source compatibility. In fact, some languages contain flaws that make it impossible, in general, to evolve a class over time without breaking at least some client code.
22. What are Deligates ?
Answer :

Delegates enable scenarios that C++ and some other languages have addressed with function pointers. Unlike function pointers, delegates are object-oriented, type-safe, and secure.
Delegates are reference types that derive from a common base class: System.Delegate. A delegate instance encapsulates a method—a callable entity. For instance methods, a callable entity consists of an instance and a method on the instance. For static methods, a callable entity consists of a class and a static method on the class.
An interesting and useful property of a delegate is that it does not know or care about the type of the object that it references. Any object will do; all that matters is that the method’s signature matches the delegate’s. This makes delegates perfectly suited for “anonymous” invocation. This is a powerful capability.
There are three steps in defining and using delegates: declaration, instantiation, and invocation. Delegates are declared using delegate declaration syntax.
delegate void SimpleDelegate();
declares a delegate named SimpleDelegate that takes no arguments and returns void.

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;
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() {…}
[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 );
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.

.Net Interview Questions

1. If A.equals(B) is true then A.getHashcode & B.getHashCode must always return same hash code.
The answer is False because it is given that A.equals(B) returns true i.e. objects are equal and now its hashCode is asked which is always independent of the fact that whether objects are equal or not. So, GetHashCode for both of the objects returns different value.
2. What is an indexer in C#?

Indexer is a special syntax for overloading [] operator for a class. After defining an indexer, array syntaxes can be used for the class objects.
3. What is the use of fixed statement?

The fixed statement sets a pointer to a managed variable and “pins” that variable during the execution of statement.
Without fixed, pointers to managed variables would be of little use since garbage collection could relocate the variables unpredictably. (In fact, the C# compiler will not allow you to set a pointer to a managed variable except in a fixed statement.)
Class A { public int i; }
A objA = new A; // A is a .net managed type
fixed(int *pt = &objA.i) // use fixed while using pointers with managed
// variables
*pt=45; // in this block use the pointer the way u want
4. What is the order of destructors called in a polymorphism hierarchy?

Destructors are called in reverse order of constructors. First destructor of most derived class is called followed by its parent’s destructor and so on till the topmost class in the hierarchy.
You don’t have control over when the first destructor will be called, since it is determined by the garbage collector. Sometime after the object goes out of scope GC calls the destructor, then its parent’s destructor and so on.
When a program terminates definitely all object’s destructors are called.
5. How can you sort the elements of the array in descending order?

int[] arr = new int[3];
arr[0] = 4;
arr[1] = 1;
arr[2] = 5;
6. Is it possible to Override Private Virtual methods.

No, First of all you cannot declare a method as ‘private virtual’.
7. What is the difference between shadow and override?
Overriding is used to redefines only the methods, but shadowing redefines the entire element.
8. Is it possible to debug the classes written in other .Net languages in a C# project.
It is definitely possible to debug other .Net languages code in a C# project. As everyone knows .net can combine code written in several .net languages into one single assembly. Same is true with debugging.
9. What is the syntax to inherit from a class in C#?
Place a colon and then the name of the base class.
Example: class NewClassName : BaseClassName
10. Describe the accessibility modifier “protected internal”.
It is available to classes that are within the same assembly and derived from the specified base class.
11. What is a satellite Assembly?
An assembly containing localized resources for another assembly.
12. How to declares a two-dimensional array in C#?

Syntax for Two Dimensional Array in C Sharp is int[,] ArrayName;
13. What does it meant to say “the canonical” form of XML?

The purpose of Canonical XML is to define a standard format for an XML document. Canonical XML is a very strict XML syntax, which lets documents in canonical XML be compared directly.
Using this strict syntax makes it easier to see whether two XML documents are the same. For example, a section of text in one document might read Black & White, whereas the same section of text might read Black & White in another document, and even in another. If you compare those three documents byte by byte, they’ll be different. But if you write them all in canonical XML, which specifies every aspect of the syntax you can use, these three documents would all have the same version of this text (which would be Black & White) and could be compared without problem. This Comparison is especially critical when xml documents are digitally signed. The digital signal may be interpreted in different way and the document may be rejected.
14. What are Delegates?

Delegates are just like function pointers in C++, except that they are much safer to use due to their type safety. A delegate defines a function without implementing it and another class then provides the implementation. Events in C# are based on delegates, with the originator defining one or more callback functions.
15. What is C#?

C# ( pronounced as C-sharp ) is a new Java like language from Microsoft. Microsoft says that C# is a language with the power of C++ and simplicity of Visual Basic. C# supposed to be the best language for Microsoft’s .NET programming.
16. What is the difference between Java and .NET garbage collectors?

Sun left the implementation of a specific garbage collector up to the JRE developer, so their performance varies widely, depending on whose JRE you’re using. Microsoft standardized on their garbage collection.
17. Why do one get a syntax error when trying to declare a variable called checked?
Syntax Error is thrown because the word checked is a keyword in C#.
18. If a method is marked as protected internal how can it be accessed?
Method marked as Protected internally can be accessed by the Classes within the same assembly, and classes derived from the declaring class.
19. What is boxing?

Encapsulating a copy of a value type in an object.
20. How can I make sure my C# classes will interoperate with other .NET languages?

Make sure your C# code conforms to the Common Language Subset (CLS). To help with this, add the [assembly:CLSCompliant(true)] global attribute to your C# source files. The compiler will emit an error if you use a C# feature which is not CLS-compliant.

Thursday, July 2, 2009

What is the Use of IComponent Interface

The functionality that IComponent adds to your class is that it can be used in component designer. It can be added to the Visual Studio's Toolbox area and it can be manipulated in design time. Without IComponent interface you cannot do this. Look at the items in your toolbox they all support IComponent which tells that they are components.

Name and describe Access modifiers in C#

Access is not restricted.

Access is limited to the containing class or types derived from the containing class.

Access is limited to the current assembly.

protected internal
Access is limited to the current assembly or types derived from the containing class.

Access is limited to the containing type.

Wednesday, July 1, 2009

What is the difference between static and class method

static objects or members of a class that can be accessed directly from the class, while non-static members can only be accessed from the instance it belongs to.

C# follows a similar principle for the methods. The static methods can by accessed directly from the class, while non-static methods (or instance methods as I like to call them) have to be accessed from an instance. That is why instatiating needs to be done for instance methods, while for static methods it's just not needed, and furthermore impractical (see below).

In OOP, static variables are used for values which cannot be stored by an instance variable. Example: supposed you wanted to keep a count of how many instances of a class exists? How would you store that in a single instance?

The methods use a similar principle. They should be used for procedures for which it is impractical to do within an instance of a class. I tend to use them for broad procedures (not a technical term), meaning those that do not require me to instantiate an object. Example, adding two parameters. (This usage may or may not be correct, but I believe it is)

However, if you wanted to add two properties of an object, the method cannot be static, because as you would soon realize, static methods cannot access instance methods or variables within a class. Of course that makes sense because that static method would not know which instance of the class the get these from unless it were told, since it is not part of an instance itself)
Locations of visitors to this page