What's C# ? C# (pronounced C-sharp) is a new object oriented language from Microsoft and is derived from C and C++.

It also borrows a lot of concepts from Java too including garbage collection. Is it possible to inline assembly or IL in C# code? - No. Is it possible to have different access modifiers on the get/set methods of a property? - 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. Is it possible to have a static indexer in C#? allowed in C#. - No. Static indexers are not . If I return out of a try/finally in C#, does the code in the finally-clause run? -Yes. The code in the finally always runs. If you return out of the try block, or even if you do a goto out of the try, the finally block always runs: using System; class main { public static void Main() { try { Console.WriteLine(\"In Try block\"); return; } finally { Console.WriteLine(\"In Finally block\"); } } } Both In Try block and In Finally block will be displayed. Whether the return is in the try block or after the try-finally block, performance is not affected either way. The compiler treats it as if the return were outside the try block anyway. If it‟s a return without an expression (as it is above), the IL emitted is identical whether the return is inside or outside of the try. If the return has an expression, there‟s an extra store/load of the value of the expression (since it has to be computed within the try block). What are Namespaces? A) Naming convention used in .Net B) Group of classes categorized to avoid name clash C) None of the above C. None of the above A Namespace in .Net is like containers of objects. They may contain unions, classes, structures, interfaces, enumerators and delegates. Main goal of using namespace in .Net is for creating a hierarchical organization of program. In this case a developer does not need to worry about the

naming conflicts of classes, functions, variables etc., inside a project. 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 a list of strings stored in a one-dimensional array, a private member variable named myStrings. A list 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 the list 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 collector 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 completing task), then 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: The garbage collector keeps track of objects that have Finalize methods, using an internal structure called the finalization queue. Each time your application creates an object that has a Finalize method, the garbage collector places an entry in the finalization queue that points to that object. The finalization queue contains entries for all the objects in the managed heap that need to have their finalization code called before the garbage collector can reclaim their memory. Implementing Finalize methods or destructors can have a negative impact on performance and you should avoid using them unnecessarily. Reclaiming the memory used by objects with Finalize methods requires at least two garbage collections. When the garbage collector performs a collection, it reclaims the memory for inaccessible objects without finalizers. At this time, it cannot collect the inaccessible objects that do have finalizers. Instead, it removes the entries for these objects from the finalization queue and places them in a list of objects marked as ready for finalization. Entries in this list point to the objects in the managed heap that are ready to have their finalization code called. The garbage collector calls the Finalize methods for the objects in this list and then removes the entries from the list. A future garbage collection will determine that the finalized objects are truly garbage because they are no longer pointed to by entries in the list of objects marked as ready for finalization. In this future garbage collection, the objects' memory is actually reclaimed. Dispose() is called by the user of an object to indicate that he is finished with it, enabling that object to release any unmanaged resources it holds. Finalize() is called by the run-time to allow an object which has not had Dispose() called on it to do the same. However Dispose() operates determinalistically, whereas there is no guarantee that Finalize() will be called

immediately when an object goes out of scope - or indeed at all, if the program ends before that object is GCed - and as such Dispose() is generally preferred. 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: Interface: -- 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 interface class, all methods are abstract - there is no implementation. 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. Interface: 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 targeted 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 outside 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. I was trying to use an out int parameter in one of my functions. How should I declare the variable that I am passing to it? You should declare the variable as an int, but when you pass it in you must specify it as „out‟, like the following: int i; foo(out i); where foo is declared as follows: [return-type] foo(out int o) { } How does one compare strings in C#? 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 How do you specify a custom attribute for the entire assembly (rather than for a class)? Global attributes must appear after any top-level using clauses and before the first type or namespace declarations. An example of this is as follows: using System; [assembly : MyAttributeClass] class X {} Note that in an IDE-created project, by convention, these attributes are placed in AssemblyInfo.cs.

How do you mark a method obsolete? [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. How do you implement thread synchronization (Object.Wait, Notify,and CriticalSection) in C#? You want the lock statement, which is the same as Monitor Enter/Exit: lock(obj) { // code } What’s the .NET collection class that allows an element to be accessed using a unique key? HashTable. What class is underneath the SortedList class? A sorted HashTable.

Will the finally block get executed if an exception has not occurred? Yes. What’s the C# syntax to catch any possible exception? A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}. Explain the three services model commonly know as a three-tier application. Presentation (UI), Business (logic and underlying code) and Data (from storage or other sources). When do you absolutely have to declare a class as abstract? 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. What is an interface class? 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. Why can’t you specify the accessibility modifier for methods inside the interface? They all must be public, and are therefore public by default. What happens if you inherit multiple interfaces and they have conflicting method names? It‟s up to you to implement the method inside your own class, so implementation is left entirely up to you. This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data, but as far as compiler cares you‟re okay. To Do: Investigate what’s the difference between an interface and abstract class? 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. What is the difference between a Struct and a Class? Struts are value-type variables and are thus saved on the stack, additional overhead but faster retrieval. Another difference is that struts cannot inherit. What’s the implicit name of the parameter that gets passed into the set method/property of a class? Value. The data type of the value parameter is defined by whatever data type the property is declared as. What does the keyword “virtual” declare for a method or property? The method or property can be overridden. How is method overriding different from method overloading? 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. Can you declare an override method to be static if the original method is not static? No. The signature of the virtual method must remain the same. (Note: Only the keyword virtual is changed to keyword override) What are the different ways a method can be overloaded? Different parameter data types, different number of parameters, different order of parameters. If a base class has a number of overloaded constructors, and an inheriting class has a number of overloaded constructors; can you enforce a call from an inherited constructor to a specific base constructor? Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class. What’s a delegate? A delegate object encapsulates a reference to a method. What’s a multicast delegate? A delegate that has multiple handlers assigned to it. Each assigned handler (method) is called. Why are there five tracing levels in System.Diagnostics.TraceSwitcher? The tracing dumps can be quite verbose. For applications that are constantly running you run the risk of overloading the machine and the hard drive. Five levels range from None to Verbose, allowing you to fine-tune the tracing activities. Where is the output of TextWriterTraceListener redirected? To the Console or a text file depending on the parameter passed to the constructor. How do you debug an ASP.NET Web application? Attach the aspnet_wp.exe process to the DbgClr debugger. What are three test cases you should go through in unit testing? 1. Positive test cases (correct data, correct output).

2. Negative test cases (broken or missing data, proper handling). 3. Exception test cases (exceptions are thrown and caught properly). Can you change the value of a variable while debugging a C# application? Yes. If you are debugging via Visual Studio.NET, just go to Immediate window. What is the role of the DataReader class in ADO.NET connections? It returns a read-only, forward-only rowset from the data source. A DataReader provides fast access when a forward-only sequential read is needed. What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET? SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix. OLE-DB.NET is a .NET layer on top of the OLE layer, so it‟s not as fastest and efficient as SqlServer.NET. What is the wildcard character in SQL? Let‟s say you want to query database with LIKE for all employees whose name starts with La. The wildcard character is %, the proper query with LIKE would involve „La%‟. Explain ACID rule of thumb for transactions. A transaction must be: 1. Atomic - it is one unit of work and does not dependent on previous and following transactions. 2. Consistent - data is either committed or roll back, no “in-between” case where something has been updated and something hasn‟t. 3. Isolated - no transaction sees the intermediate results of the current transaction). 4. Durable - the values persist if the data had been committed even if the system crashes right after. What connections does Microsoft SQL Server support? Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and password). Between Windows Authentication and SQL Server Authentication, which one is trusted and which one is untrusted? Windows Authentication is trusted because the username and password are checked with the Active Directory, the SQL Server authentication is untrusted, since SQL Server is the only verifier participating in the transaction. What does the Initial Catalog parameter define in the connection string? The database name to connect to. What does the Dispose method do with the connection object? Deletes it from the memory. How is the DLL Hell problem solved in .NET? Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly.

What are the ways to deploy an assembly? An MSI installer, a CAB archive, and XCOPY command. What namespaces are necessary to create a localized application? System.Globalization and System.Resources. What is the smallest unit of execution in .NET? An Assembly. When should you call the garbage collector in .NET? As a good rule, you should not call the garbage collector. However, you could call the garbage collector when you are done using a large object (or set of objects) to force the garbage collector to dispose of those very large objects from memory. However, this is usually not a good practice. How do you convert a value-type to a reference-type? Use Boxing. Is there regular expression (regex) support available to C# developers? Yes. The .NET class libraries provide support for regular expressions. Look at the documentation for the System.Text.RegularExpressions namespace. Is there a way to force garbage collection? Yes. Set all references to null and then call System.GC.Collect(). If you need to have some objects destructed, and System.GC.Collect() doesn't seem to be doing it for you, you can force finalizers to be run by setting all the references to the object to null and then calling System.GC.RunFinalizers(). Does C# support properties of array types? Yes. Here's a simple example: using System; class Class1 { private string[] MyField; public string[] MyProperty { get { return MyField; } set { MyField = value; } }} class MainClass { public static int Main(string[] args) { Class1 c = new Class1(); string[] arr = new string[] {"apple", "banana"}; c.MyProperty = arr; Console.WriteLine(c.MyProperty[0]); // "apple" return 0; }} What connections does Microsoft SQL Server support?

Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and passwords) What is a satellite assembly? When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies. How is method overriding different from overloading? When overriding, you change the method behavior for a derived class. Overloading simply involves having a method with the same name within the class. When do you absolutely have to declare a class as abstract (as opposed to free-willed educated choice or decision based on UML diagram)? When at least one of the methods in the class is abstract. When the class itself is inherited from an abstract class, but not all base abstract methods have been over-ridden. Why would you use untrusted verification? Web Services might use it, as well as non-Windows applications. What is the implicit name of the parameter that gets passed into the class set method? Value, and its datatype depends on whatever variable we are changing. How do I register my code for use by classic COM clients? Use the regasm.exe utility to generate a type library (if needed) and the necessary entries in the Windows Registry to make a class available to classic COM clients. Once a class is registered in the Windows Registry with regasm.exe, a COM client can use the class as though it were a COM class. How do I create a multi language, multi file assembly? Unfortunately, this is currently not supported in the IDE. To do this from the command line, you must compile your projects into netmodules (/target:module on the C# compiler), and then use the command line tool al.exe (alink) to link these netmodules together. C# provides a default constructor for me. I write a constructor that takes a string as a parameter, but want to keep the no parameter one. How many constructors should I write? Two. Once you write at least one constructor, C# cancels the freebie constructor, and now you have to write one yourself, even if there is no implementation in What is the equivalent to regsvr32 and regsvr32 /u a file in .NET development? Try using RegAsm.exe. The general syntax would be: RegAsm. A good description of RegAsm and its associated switches is located in the .NET SDK docs. Just search on "Assembly Registration Tool".Explain ACID rule of thumb for transactions. Transaction must be Atomic (it is one unit of work and does not dependent on previous and following transactions), Consistent (data is either committed or roll back, no in-between case where something has been updated and something hasnot), Isolated (no transaction sees the intermediate results of the current transaction), Durable (the values persist if the data had been committed even if the system crashes right after).

Where is the output of TextWriterTraceListener redirected? To the Console or a text file depending on the parameter passed to the constructor. How do I create a multilanguage, single-file assembly? This is currently not supported by Visual Studio .NET. Why cannot you specify the accessibility modifier for methods inside the interface? They all must be public. Therefore, to prevent you from getting the false impression that you have any freedom of choice, you are not allowed to specify any accessibility, it is public by default. Is it possible to restrict the scope of a field/method of a class to the classes in the same namespace? 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. Why do I get a syntax error when trying to declare a variable called checked? The word checked is a keyword in C#. Why are there five tracing levels in System.Diagnostics.TraceSwitcher? The tracing dumps can be quite verbose and for some applications that are constantly running you run the risk of overloading the machine and the hard drive there. Five levels range from None to Verbose, allowing to fine-tune the tracing activities. What is the syntax for calling an overloaded constructor within a constructor (this() and constructorname() does not compile)? The syntax for calling another constructor is as follows: class B { B(int i) {} } class C : B { C() : base(5) // call base constructor B(5) {} C(int i) : this() // call C() {} public static void Main() {} } 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: class test { static void Main(string[] args) {} } 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: lab1: turns into: gotoif !A, lab2 lab1: 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]); p.WaitForExit(); Console.WriteLine(args[0] + " exited."); }} Remember to add a reference to System.Diagnostics.dll when you compile.

What is the difference between the System.Array.CopyTo() and System.Array.Clone()? The first one performs a deep copy of the array, the second one is shallow. 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); Console.WriteLine(s1); Console.WriteLine(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; class BreakExample {

public static void Main(String[] args) { for(int i=0; i<3;> { Console.WriteLine("Pass {0}: ", i); for( int j=0 ; j<100> { if ( j == 10) goto done; Console.WriteLine("{0} ", j); } Console.WriteLine("This will not print"); } done: Console.WriteLine("Loops complete."); }} 1. No. Does C# support multiple-inheritance?

2. Who is a protected class-level variable available to? It is available to any sub-class (a class inheriting this class). 3. Are private class-level variables inherited? Yes, but they are not accessible. Although they are not visible or accessible via the class interface, they are inherited. 4. Describe the accessibility modifier “protected internal”. It is available to classes that are within the same assembly and derived from the specified base class. 5. What’s the top .NET class that everything is derived from? System.Object. 6. What does the term immutable mean? The data value may not be changed. Note: The variable value may be changed, but the original immutable data value was discarded and a new data value was created in memory. 7. What’s the difference between System.String and System.Text.StringBuilder classes? System.String is immutable. System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed. 8. What’s the advantage of using System.Text.StringBuilder over System.String? StringBuilder is more efficient in cases where there is a large amount of string manipulation. Strings are immutable, so each time a string is changed, a new instance in memory is created. 9. Can you store multiple data types in System.Array? No. 10. What’s the difference between the System.Array.CopyTo() and System.Array.Clone()? The Clone() method returns a new array (a shallow copy) object containing all the elements in the original

array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identacle object.

11. What’s the .NET collection class that allows an element to be accessed using a unique key? HashTable. 12. What class is underneath the SortedList class? A sorted HashTable. 13. Will the finally block get executed if an exception has not occurred? Yes. 14. What’s the C# syntax to catch any possible exception? A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}. 15. Can multiple catch blocks be executed for a single try statement? No. Once the proper catch block processed, control is transferred to the finally block (if there are any). 16. Explain the three services model commonly know as a three-tier application. Presentation (UI), Business (logic and underlying code) and Data (from storage or other sources). What does the modifier protected internal in C# mean? The Protected Internal can be accessed by Members of the Assembly or the inheriting class, and of course, within the class itself. In VB.NET, the equivalent of protected internal is protected friend. The access of this modifier is limited to the current assembly or the types derived from the defining class in the current assembly. To know more on different types of access specifiers Can multiple data types be stored in System.Array? So whats an array all about? An array is a collection of items of the same type, that is grouped together and encompassed within an array object. The array object, or the System.Array object to be precise, is derived from the System.Object class. It is thus, stored in the form of a heap in the memory.

An array may be of single dimensional, multi-dimensional or jagged (a jagged array means an array within an array). A group of items when assigned values within braces implicitly derive from System.Array class. See example below written in C#... int[] testIntArray = new int[4] { 2, 3, 4, 5 }; Object[] testObjArray = new Object[5] { 32, 22, 23, 69, 75 }; Ideally an array should contain a single data type. But still in case there is a requirement to place data of different data types in a specific array, then in such a scenario, the data elements should be declared as an object type. When this is done, then each element may point ultimately to a different data type. See

code example below written in VB.NET... Dim allTypes As Object() = New Object() {} 'In this kind of scenario, the performance may tend to slow down, as data conversions may take place. 'In case a value type is converted to reference type, then boxing and unboxing occurs 'To know more on Value Types & Reference Types, Click Here Dim studentTable(2) As Object studendTable(0) = "Vishal Khanna" studentTable(1) = 28 studentTable(2) = #9/1/1978# 'To get these values of these varying datatypes, their values are converted to their original data type Dim myAge As Integer = CInt(studentTable(1)) Dim myBirthDay as Date = CDate(studentTable(2)) How to sort array elements in descending order in C#? Elements of an array may not be sorted by default. To sort them in descending order, the Sort() method is first called. Next, to descend the order, call the Reverse() method Whats the use of "throw" keyword in C#? The throw keyword is used to throw an exception programatically in C#. In .NET, there is an in-built technique to manage & throw exceptions. In C#, there are 3 keyword, that are used to implement the Exception Handling. These are the try, catch and finally keywords. In case an exception has to be implicitly thrown, then the throw keyword is used. See code example below, for throwing an exception programatically... class SomeClass { public static void Main() { try { throw new DivideByZeroException("Invalid Division Occured"); } catch(DivideByZeroException e) { Console.WriteLine("Exception - Divide by Zero" ); } } } Can we put multiple catch blocks in a single try statement in C#? Yes. Multiple catch blocks may be put in a try block. See code example below, to see multiple catch blocks being used in C#. class ClassA { public static void Main() {

int y = 0; try { val = 100/y; Console.WriteLine("Line not executed"); } catch(DivideByZeroException ex) { Console.WriteLine("DivideByZeroException" ); } catch(Exception ex) { Console.WritLine("Some Exception" ); } finally { Console.WriteLine("This Finally Line gets executed always"); } Console.WriteLine("Result is {0}",val); } } How to achieve polymorphism in C#? In C#, polymorphism may be achieved by overloading a function, overloading an operator, changing the order of types, changing the types using the same name for the member in context. To see some code examples of polymorphism, Click Here. What is polymorphism? Polymorphism means allowing a single definition to be used with different types of data (specifically, different classes of objects). For example, a polymorphic function definition can replace several typespecific ones, and a single polymorphic operator can act in expressions of various types. Many programming languages implement some forms of polymorphism. The concept of polymorphism applies to data types in addition to functions. A function that can evaluate to and be applied to values of different types is known as a polymorphic function. A data type that contains elements of different types is known as a polymorphic data type. Polymorphism may be achieved by overloading a function, overloading an operator, changing the order of types, changing the types using the same name for the member in context. Example: Public Class Calc { public void fnMultiply(int x, int y) { return x * y; } public void fnMultiply(int x, int y, int z) { return x * y * z; } } ... ...

Calc obj; int Result; Result = obj.fnMultiply(2,3,4); // The second fnMultiply would be called Result = obj.fnMultiply(3,4); // The first fnMultiply would be called //Here, the call depends on the number of parameters passed, polymorphism is achieved using overloading How to add a ReadOnly property in C#? Property - A property is an entity that describes the features of an object. A property is a piece of data contained within a class that has an exposed interface for reading/writing. Looking at that definition, you might think you could declare a public variable in a class and call it a property. While this assumption is somewhat valid, the true technical term for a public variable in a class is a field. The key difference between a field and a property is in the inclusion of an interface. We make use of Get and Set keywords while working with properties. We prefix the variables used within this code block with an underscore. Value is a keyword, that holds the value which is being retrieved or set. See code below to set a property as ReadOnly. If a property does not have a set accessor, it becomes a ReadOnly property. public class ClassA { private int length = 0; public ClassA(int propVal) { length = propVal; } public int length { get { return length; } } } How to prevent a class from being inherited? Sealed in C#? In order to prevent a class in C# from being inherited, the sealed keyword is used. Thus a sealed class may not serve as a base class of any other class. It is also obvious that a sealed class cannot be an abstract class. Code below... sealed class ClassA { public int x; public int y; } No class can inherit from ClassA defined above. Instances of ClassA may be created and its members may then be accessed, but nothing like the code below is possible... class DerivedClass: ClassA {} // Error Can we inherit multiple interfaces in C#? Yes. Multiple interfaces may be inherited in C#.

Note that when a class and multiple interfaces are to be inherited, then the class name should be written first, followed by the names of the interfaces. See code example below, on how to inherit multiple interfaces in C#. class someclass : parentclass, IInterface1, IInterface2 { //...Some code in C# } What are the different ways of overloading methods in C#? What is function overloading in C#? Before knowing the different methods of overloading in C#, lets first clear out what exactly overloading is. Overloading is the OOPs concept of using a method or a class in different styles by modifying the signature of the parameters in it. To know more on overloading, Click Here. In order to achieve overloading, there may be several techniques applied. There are different types of overloading like Operator Overloading, Function Overloading etc. Function overloading may be achieved by changing the order of parameters in a function, by changing the types passed in the function, and also by changing the number of parameters passed in a function. See code sample below to see types of overloading. //Define a method below public void fnProcess(int x, double y) { ...... } //change the order of parameters public void fnProcess(double x, int y) { //.......Some code in C# } //Similarly, we may change the number of parameters in fnProcess //and alter its behaviour How to call a specific base constructor in C#? What is a Constructor? - It is a method that gets invoked when an instance of a class is created. In case a class has plenty of constructors, i.e. there are plenty of overloaded constructors, in such a scenario, it is still possible to invoke a specific base constructor. But there is a special way, as explicit calls to a base constructor is not possible in C#. See code below: public class dotnetClass { public dotnetClass() { // The constructor method here } // Write the class members here }

//Sample code below shows how to overload a constructor public class dotnetClass { public dotnetClass() { // This constructor is without a parameter // Constructor #1 } public dotnetClass(string name) { // This constructor has 1 parameter. // Constructor #2 } } This constructor gets executed when an object of this class is instantiated. This is possible in C#. Calling a specific constructor will depend on how many parameters, and what parameters match a specific constructor. Note that a compile time error may get generated when 2 constructors of the same signature are created. We may make use of the this keyword and invoke a constructor. See code example below. this("some dotnet string"); //This will call Constructor #2 above What is the use of the base keyword. Suppose we have a derived class named dotnetderivedclass. If this derived class is to invoke the constructor of a base class, we make use of the base keyword. See code example below on how to use a base keyword to invoke the base class constructor. public class dotnetClass { public dotnetClass() { // The 1st base class constructor defined here } public dotnetClass(string Name) { // The 2nd base class constructor defined here } } public class dotnetderivedclass : dotnetClass // A class is being inherited out here { public dotnetderivedclass() { // dotnetderivedclass 1st constructor defined here }

public dotnetderivedclass(string name):base(name) { // dotnetderivedclass 2nd constructor defined here } } Note that we have used the base keyword in the sample code above. The sequence of execution of the constructors will be as follows: public dotnetClass() method -> public dotnetderivedclass() method The above sequence triggers when there is no initializer to the base class, and thus it triggers the parameterless base class constructor. The other base class constructor may also get invoked when we pass a parameter while defining it. What is a static constructor? Static Constructor - It is a special type of constructor, introduced with C#. It gets called before the creation of the first object of a class(probably at the time of loading an assembly). See example below. Example: public class SomeClass() { static SomeClass() { //Static members may be accessed from here //Code for Initialization } } While creating a static constructor, a few things need to be kept in mind: * There is no access modifier require to define a static constructor * There may be only one static constructor in a class * The static constructor may not have any parameters * This constructor may only access the static members of the class * We may create more than one static constructor for a class Can a class be created without a constructor? No. In case we dont define the constructor, the class will access the no-argument constructor from its base class. The compiler will make this happen during compilation. What are generics in C#? Generics in C# is a new innovative feature through which classes and methods in C# may be designed in such a way that the rules of a type are not followed until it is declared. The generics feature in C# has been introduced with version 2.0 of the .NET Framework. Using generics, a class template may be declared that may follow any type as required at runtime. The class behavior is later governed by the type that we pass to the class. Once the type is passed, the class behaves depending on the type passed to this generic class. 1 Structs are largely redundant in C++. Why does C# have them? 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. 2 Does C# support multiple inheritance (MI)? No, though it does support implementation of multiple interfaces on a single class or struct. 3 Is a C# interface the same as a C++ abstract class? No, not quite. An abstract class in C++ cannot be instantiated, but it can (and often does) contain implementation code and/or data members. A C# interface cannot contain any implementation code or data members - it is simply a group of method names & signatures. A C# interface is more like a COM interface than a C++ abstract class. 4 Are C# constructors the same as C++ constructors? 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 - see Can I Call a virtual method from a constructor. 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. (Thanks to Jon Jagger for pointing this out.) 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. See Brad Wilson's article. 6 If C# destructors are so different to C++ destructors, why did MS use the same syntax? Presumably they wanted C++ programmers to feel at home. I think they made a mistake. 7 Are all methods virtual in C#? No. Like C++, methods are non-virtual by default, but can be marked as virtual. 8 How do I declare a pure virtual function in C#? 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). 9 Can I call a virtual method from a constructor/destructor? 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. 10 Should I make my destructor virtual? A C# destructor is really just an override of the System.Object Finalize method, and so is virtual by definition. 1. What is the syntax to inherit from a class in C#? Place a colon and then the name of the base class. Example: class MyNewClass : MyBaseClass 2. Can you prevent your class from being inherited by another class? Yes. The keyword “sealed” will prevent the class from being inherited. 3. Can you allow a class to be inherited, but prevent the method from being over-ridden? Yes. Just leave the class public and make the method sealed. 4. 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. 5. When do you absolutely have to declare a class as abstract? 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? 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. Why can’t you specify the accessibility modifier for methods inside the interface? They all must be public, and are therefore public by default. 8. Can you inherit multiple interfaces? Yes. .NET does support multiple interfaces. 9. What happens if you inherit multiple interfaces and they have conflicting method names? It‟s up to you to implement the method inside your own class, so implementation is left entirely up to you. This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data, but as far as compiler cares you‟re okay. To Do: Investigate 10. What’s the difference between an interface and abstract class? 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.

11. What is the difference between a Struct and a Class? Structs are value-type variables and are thus saved on the stack, additional overhead but faster retrieval. Another difference is that structs cannot inherit 1. What’s the implicit name of the parameter that gets passed into the set method/property of a class? Value. The data type of the value parameter is defined by whatever data type the property is declared as. 2. What does the keyword “virtual” declare for a method or property? The method or property can be overridden. 3. How is method overriding different from method overloading? 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. 4. 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) 5. What are the different ways a method can be overloaded? Different parameter data types, different number of parameters, different order of parameters. 6. 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. 7. What’s a delegate? A delegate object encapsulates a reference to a method. 8. What’s a multicast delegate? A delegate that has multiple handlers assigned to it. Each assigned handler (method) is called. Debugging and Testing 1. What debugging tools come with the .NET SDK? 1. CorDBG – command-line debugger. To use CorDbg, you must compile the original C# file using the /debug switch. 2. DbgCLR – graphic debugger. Visual Studio .NET uses the DbgCLR. 2. What does assert() method 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. 3. What’s the difference between the Debug class and Trace class? Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds.

4. Why are there five tracing levels in System.Diagnostics.TraceSwitcher? The tracing dumps can be quite verbose. For applications that are constantly running you run the risk of overloading the machine and the hard drive. Five levels range from None to Verbose, allowing you to fine-tune the tracing activities. 5. Where is the output of TextWriterTraceListener redirected? To the Console or a text file depending on the parameter passed to the constructor. 6. How do you debug an ASP.NET Web application? Attach the aspnet_wp.exe process to the DbgClr debugger. 7. What are three test cases you should go through in unit testing? 1. Positive test cases (correct data, correct output). 2. Negative test cases (broken or missing data, proper handling). 3. Exception test cases (exceptions are thrown and caught properly). 8. Can you change the value of a variable while debugging a C# application? Yes. If you are debugging via Visual Studio.NET, just go to Immediate window. 1 Can I use exceptions in C#? 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. 2 What types of object can I throw as exceptions? 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. 3 Can I define my own exceptions? Yes, just derive your exception class from System.Exception. 4 Does the System.Exception class have any cool features? Yes - the feature which stands out is the StackTrace property. This provides a call stack which records where the exception was thrown from. For example, the following code: using System; class CApp { public static void Main() { try { f(); } catch( Exception e ) { Console.WriteLine( "System.Exception stack trace = \n{0}", e.StackTrace ); } }

static void f() { throw new Exception( "f went pear-shaped" ); } } produces this output: System.Exception stack trace = at CApp.f() at CApp.Main() Note, however, that this stack trace was produced from a debug build. A release build may optimise away some of the method calls which could mean that the call stack isn't quite what you expect. 5 When should I throw an exception? 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. 6 Does C# have a 'throws' clause? No, unlike Java, C# does not require (or even allow) the developer to specify the exceptions that a method can throw. Run-time Type Information 7 How can I check the type of an object at runtime? You can use the is keyword. For example: using System; class CApp { public static void Main() { string s = "fred"; long i = 10; Console.WriteLine( "{0} is {1}an integer", s, (IsInteger(s) ? "" : "not ") ); Console.WriteLine( "{0} is {1}an integer", i, (IsInteger(i) ? "" : "not ") ); } static bool IsInteger( object obj ) { if( obj is int obj is long ) return true; else return false; } }

produces the output: fred is not an integer 10 is an integer 8 Can I get the name of a type at runtime? Yes, use the GetType method of the object class (which all types inherit from). For example: using System; class CTest { class CApp { public static void Main() { long i = 10; CTest ctest = new CTest(); DisplayTypeInfo( ctest ); DisplayTypeInfo( i ); } static void DisplayTypeInfo( object obj ) { Console.WriteLine( "Type name = {0}, full type name = {1}", obj.GetType(), obj.GetType().FullName ); } } } produces the following output: Type name = CTest, full type name = CTest Type name = Int64, full type name = System.Int64 How do you implement thread synchronization (Object.Wait, Notify,and CriticalSection) in C#? You want the lock statement, which is the same as Monitor Enter/Exit: lock(obj) { // code } translates to try { CriticalSection.Enter(obj); // code } finally { CriticalSection.Exit(obj); } How do you directly call a native function exported from a DLL? Here’s a quick example of the DllImport attribute in action: using System.Runtime.InteropServices; \

class C { [DllImport(\"user32.dll\")] public static extern int MessageBoxA(int h, string m, string c, int type); public static int Main() { return MessageBoxA(0, \"Hello World!\", \"Caption\", 0); }} This example shows the minimum requirements for declaring a C# method that is implemented in a native DLL. The method C.MessageBoxA() is declared with the static and external modifiers, and has the DllImport attribute, which tells the compiler that the implementation comes from the user32.dll, using the default name of MessageBoxA. For more information, look at the Platform Invoke tutorial in the documentation. How do I simulate optional parameters to COM calls? You must use the Missing class and pass Missing.Value (in System.Reflection) for any values that have optional parameters. What do you know about .NET assemblies? Assemblies are the smallest units of versioning and deployment in the .NET application. Assemblies are also the building blocks for programs such as Web services, Windows services, serviced components, and .NET remoting applications. What’s the difference between private and shared assembly? Private assembly is used inside an application only and does not have to be identified by a strong name. Shared assembly can be used by multiple applications and has to have a strong name. What’s a strong name? A strong name includes the name of the assembly, version number, culture identity, and a public key token. How can you tell the application to look for assemblies at the locations other than its own install? Use the directive in the XML .config file for a given application. < privatepath="c:\mylibs;"> should do the trick. Or you can add additional search paths in the Properties box of the deployed application. How can you debug failed assembly binds? Use the Assembly Binding Log Viewer (fuslogvw.exe) to find out the paths searched. Where are shared assemblies stored? Global assembly cache. How can you create a strong name for a .NET assembly? With the help of Strong Name tool (sn.exe). Where’s global assembly cache located on the system? Usually C:\winnt\assembly or C:\windows\assembly.

Can you have two files with the same file name in GAC? Yes, remember that GAC is a very special folder, and while normally you would not be able to place two files with the same name into a Windows folder, GAC differentiates by version number as well, so it‟s possible for MyApp.dll and MyApp.dll to co-exist in GAC if the first one is version 1.0.0.0 and the second one is 1.1.0.0. So let‟s say I have an application that uses MyApp.dll assembly, version 1.0.0.0. There is a security bug in that assembly, and I publish the patch, issuing it under name MyApp.dll 1.1.0.0. How do I tell the client applications that are already installed to start using this new MyApp.dll? Use publisher policy. To configure a publisher policy, use the publisher policy configuration file, which uses a format similar app .config file. But unlike the app .config file, a publisher policy file needs to be compiled into an assembly and placed in the GAC. What is delay signing? Delay signing allows you to place a shared assembly in the GAC by signing the assembly with just the public key. This allows the assembly to be signed with the private key at a later stage, when the development process is complete and the component or assembly is ready to be deployed. This process enables developers to work with shared assemblies as if they were strongly named, and it secures the private key of the signature from being accessed at different stages of development. Is there an equivalent of exit() for quitting a C# .NET application? Yes, you can use System.Environment.Exit(int exitCode) to exit the application or Application.Exit() if it's a Windows Forms app. Can you prevent your class from being inherited and becoming a base class for some other classes? Yes, that is what keyword sealed in the class definition is for. The developer trying to derive from your class will get a message: cannot inherit from Sealed class WhateverBaseClassName. It is the same concept as final class in Java. Is XML case-sensitive? Yes, so and are different elements. If a base class has a bunch of overloaded constructors, and an inherited class has another bunch of overloaded constructors, can you enforce a call from an inherited constructor to an arbitrary base constructor? Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class. I was trying to use an "out int" parameter in one of my functions. How should I declare the variable that I am passing to it? You should declare the variable as an int, but when you pass it in you must specify it as 'out', like the following: int i; foo(out i); where foo is declared as follows: [return-type] foo(out int o) { } How do I make a DLL in C#?

You need to use the /target:library compiler option. How do I simulate optional parameters to COM calls? You must use the Missing class and pass Missing.Value (in System.Reflection) for any values that have optional parameters. 1.How is the DLL Hell problem solved in .NET? Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly. 2. What are the ways to deploy an assembly? An MSI installer, a CAB archive, and XCOPY command. 3. What is a satellite assembly? When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies. 4. What namespaces are necessary to create a localized application? System.Globalization and System.Resources. 5. What is the smallest unit of execution in .NET? an Assembly. 6. When should you call the garbage collector in .NET? As a good rule, you should not call the garbage collector. However, you could call the garbage collector when you are done using a large object (or set of objects) to force the garbage collector to dispose of those very large objects from memory. However, this is usually not a good practice. 7. How do you convert a value-type to a reference-type? Use Boxing. 8. What happens in memory when you Box and Unbox a value-type? Boxing converts a value-type to a reference-type, thus storing the object on the heap. Unboxing converts a reference-type to a value-type, thus storing the value on the stack. 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 x1 = 3; // x1 is a value on the stack 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 2.6 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" ); else Console.WriteLine( "String is length {0}", s.Length ); } What is namespaces in .NET? It is a logical group of related classes and interfaces and that can be used by any language targeting the .net framework. Tell me about Secure Socket Layer? How to make use of the technology? Secure Sockets Layer (SSL) and Transport Layer Security (TLS), its successor, are cryptographic protocols which provide secure communications on the Internet. There are slight differences between SSL 3.0 and TLS 1.0, but the protocol remains substantially the same. The term “SSL” as used here applies to both protocols unless clarified by context. Can any object be stored in a Viewstate in .NET? An object that either is serializable or has a TypeConverter defined for it can be persisted in ViewState Explain ADO.NET features? Benefits? Drawbacks? 1. Data will be retrieved through DataSets 2. Scalability ASP.NET interview questions only? 1. How does ASP page work? 2. How ASP.NET page works? 3. What are the contents of cookie? 4. How do you create a permanent cookie? 5. What is ViewState? What does the “EnableViewState” property do? Whay would I want it on or off? 6. Give an example of what might be best suited to place in the Application_Start and Session_Start subroutines? 7. Describe the role of global.asax? 8. How can you debug your.NET application? 9. How do you deploy your ASP.NET application? How is meant by DLL in .NET? A DLL (Dynamic Link Library) in .NET is a file that can be loaded and executed by programs dynamically. Basically it‟s an external code repository for programs. Since usually several different programs reuse the same DLL instead of having that code in their own file, this dramatically reduces required storage space. A synonym for a DLL would be library in .NET How does output caching work in ASP.NET? Output caching is a powerful technique that increases request/response throughput by caching the content generated from dynamic pages. Output caching is enabled by default, but output from any given response is not cached unless explicit action is taken to make the response cacheable. To make a response eligible for output caching, it must have a valid expiration/validation policy and public cache visibility. This can be done using either the low-level OutputCache API or the high-level @ OutputCache directive. When output caching is enabled, an output cache entry is created on the first GET

request to the page. Subsequent GET or HEAD requests are served from the output cache entry until the cached request expires. The output cache also supports variations of cached GET or POST name/value pairs. The output cache respects the expiration and validation policies for pages. If a page is in the output cache and has been marked with an expiration policy that indicates that the page expires 60 minutes from the time it is cached, the page is removed from the output cache after 60 minutes. If another request is received after that time, the page code is executed and the page can be cached again. This type of expiration policy is called absolute expiration - a page is valid until a certain time. Explain how Viewstate is being formed and how it’s stored on client in .NET? The type of ViewState is System.Web.UI.StateBag, which is a dictionary that stores name/value pairs. ViewState is persisted to a string variable by the ASP.NET page framework and sent to the client and back as a hidden variable. Upon postback, the page framework parses the input string from the hidden variable and populates the ViewState property of each control. If a control uses ViewState for property data instead of a private field, that property automatically will be persisted across round trips to the client. (If a property is not persisted in ViewState, it is good practice to return its default value on postback.) Explain assemblies in .NET? Assemblies are similar to dll files. Both has the reusable pieces of code in the form of classes/ functions. Dll needs to be registered but assemblies have its own metadata. Explain DataSet.AcceptChanges and DataAdapter.Update methods in .NET? DataAdapter.Update method Calls the respective INSERT, UPDATE, or DELETE statements for each inserted, updated, or deleted row in the DataSet. DataSet.AcceptChanges method Commits all the changes made to this row since the last time AcceptChanges was called.

Sign up to vote on this title
UsefulNot useful