You are on page 1of 159

2.

C# Interview Questions

C# interview questions
1. Whats the implicit name of the parameter that gets passed into the class set method? Value, and its datatype depends on whatever variable were changing. 2. How do you inherit from a class in C#? Place a colon and then the name of the base class. 3. Does C# support multiple inheritance? No, use interfaces instead. 4. When you inherit a protected class-level variable, who is it available to? Classes in the same namespace. 5. Are private class-level variables inherited? Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited. But they are. 6. Describe the accessibility modifier protected internal. Its available to derived classes and classes within the same Assembly (and naturally from the base class its declared in). 7. 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 theres no implementation in it. 8. Whats the top .NET class that everything is derived from? System.Object. 9. Hows 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. 10. What does the keyword virtual mean in the method definition? The method can be over-ridden. 11. Can you declare the override method static while the original method is nonstatic? No, you cant, the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override. 12. Can you override private virtual methods? No, moreover, you cannot access private methods in inherited classes, have to be protected in the base class to allow any sort of access. 13. Can you prevent your class from being inherited and becoming a base class for some other classes? Yes, thats 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. Its the same concept as final class in Java. 14. Can you allow class to be inherited, but prevent the method from being overridden? Yes, just leave the class public and make the method sealed. 15. Whats an abstract class? A class that cannot be instantiated. A concept in C++ known as pure virtual method. A class that must be inherited and have the methods over-ridden. Essentially, its a blueprint for a class without any implementation. 16. 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 overridden. 17. Whats an interface class?

Its an abstract class with public abstract methods all of which must be implemented in the inherited classes. 18. Why cant 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, its public by default. 19. Can you inherit multiple interfaces? Yes, why not. 20. And if they have conflicting method names? Its 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 youre okay. 21. Whats the difference between an interface and abstract class? In the interface all methods must be abstract, in the abstract class some methods can be concrete. In the interface no accessibility modifiers are allowed, which is ok in abstract classes. 22. How can you overload a method? Different parameter data types, different number of parameters, different order of parameters. 23. 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. 24. Whats the difference between System.String and System.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.

25. Is it namespace class or class namespace? The .NET class library is organized into namespaces. Each namespace contains a functionally related group of classes so natural namespace comes first. Read all | Browse topics: .NET

28 Comments
1. Regarding #4 . When you inherit a protected class-level variable, who is it available to? Classes in the same namespace. Wrong, the protected keyword in C# specifies that only classes that ultimately inherit from the class with a protected member can see that member. Quote from the C# Programmers Reference (MSDN): protected - Access is limited to the containing class or types derived from the containing class. Tech Interviews comment by Richard Lowe 2. Again in #15 Whats an abstract class? Essentially, its a blueprint for a class without any implementation. Although an abstract class does not require implementations (its methods can be abstract) it *can* also offer implementations of methods (either virtual or not) which can be called in implementing classes. Tech Interviews comment by Richard Lowe 3. Right you are, Richard. Thanks, I will update. Tech Interviews comment by admin 4. #18 is misleading. You CAN implement an interface explicitly without the members being declared public in your class. The difference is that if the members are not public, they will only be available when you have a reference variable of the type of the interface pointing to you class You implement them like so: void IDisposable.Dispose() { // TODO: Add Class1.Dispose implementation } Tech Interviews comment by Richard Lowe

5. Oh hi, I hope my comments were helpful - Im not just some C# facist :) I would just hate to see a right answer disqualify a good candidate! Tech Interviews comment by Richard Lowe 6. #18 If the members of the interface are not public, then even if you have an instance of that, how would you implement/override non-public members if you dont have any access to them? Tech Interviews comment by admin 7. Yeah, no problem, I always welcome suggestions and corrections. Especially this set of questions which I wrote myself, by taking notes from Microsofts SelfTraining MCSD cert kit. Your comments make me go back to the books and online documentation. #4 and #15 I totally agree. #18 I will double check :-) Tech Interviews comment by admin 8. If the members of the interface are not public, then even if you have an instance of that, how would you implement/override non-public members if you dont have any access to them? Ah, you meant public to references to the *interface* so of course they must be publically visible. I read the original question as meaning public to references to the class which isnt a necessity. That was my mis-read, sorry. Tech Interviews comment by Richard Lowe 9. Is it namespace class or class namespace??? The .NET class library is organized into namespaces. Each namespace contains a functionally related group of classes so natural namespace comes first. Tech Interviews comment by Andrew O 10. correction: so natural namespace comes first should be so naturally namespace comes first Tech Interviews comment by Andrew O 11. for question 7, C# doest cancel the freebie constructor(parameter less constuctor). it is goting to keep the parameter less constructor, even if you add any number of parameterised constructors.

Tech Interviews comment by Kishore 12. I believe that Kishore is wrong in comment number 11. C# behaves this way so that you can specify a class has *no* parameterless constructor. If Kishore were correct, then it would be impossible to implement a class without a parameterless (default) constructor. Tech Interviews comment by MBearden 13. An interesting (and difficult) question to add would be: How do you specify constructors in an interface? Answer is You cannot. C# does not allow constructor signatures to be specified in interface. I dont know the reason why If anyone reading this does, could you e-mail with your comments on why C# was designed this way? Just curious. Tech Interviews comment by MBearden 14. For Question 13: As far I know interfaces doesnt have data members(fields), they will only have methods or properties, so no need for constructors. I am also new to C# so I dont know whether I am completely correct or not. Tech Interviews comment by ram 15. Follow up for #13 & #17 Ram, you are right. An instance of an interface cannot be created. (But the interface methods can be accessed in a class implementing that interface, by casting the instance of that class to the interface type. This is sometimes referred to as creating an instance of the interface.) The job of a constructor is to create the object specified by a class and to put it into a valid state.[Programming C#Jesse Liberty]. So, no need of a constructor. Use of property in an interface: An interface can have methods, properties, events and indexers. When a property in an interface is implemented in a class, the advantage is that, through that property, the class can give access to its private member varibles. Hope Iam clear. Thanks,RAD Tech Interviews comment by Rad 16. Thought Id offer a few points on your list of questions.

1) This question would be better stated What is the implicit name of the parameter passed into a propertys set method? 2) Its a good while since Ive had to do any C++, but my long term memory tells me that it isnt double colon in C++. Perhaps youre confusing the scope resolution operator? 3) A better answer would be that C# disallows multiple inheritance of implementation, but allows classes to implement multiple interfaces. 4) This is just wrong. Protected members are visible only to classes that are derived from the containing class. 15) An abstract class in C++ is a class that contains at least 1 pure virtual method. Tech Interviews comment by Tim Haughton 17. can anyone explain/differentiate between different database concepts(odbc,oledb,ado.net, ado,dao,rao)? Tech Interviews comment by Kiran Mandhadi 18. Here are more questions 1. What does the readonly keyword do for a variable in c#? (hint on Question 4) 2. Can we overload methods by specifying different return types? 3. Can you can specify values for for variables in interfaces in c#? (In Java you can) 4. What is the difference between const and readonly ? Have Fun :) Tech Interviews comment by Binoj Antony 19. Answers to Binojs Questions: What does the readonly keyword do for a variable in c#? What is the difference between const and readonly ? Answer) To declare constants in C# the const keyword is used for compile time constants while the readonly keyword is used for runtime constants Can we overload methods by specifying different return types? Answer) NO. I tried it in VS.net

Can you can specify values for for variables in interfaces in c#? (In Java you can) Answer) Yes! I am not sure of this answer, correct me if I am wrong. Would appreciate if anybody else could post more messages here Thanks, Kiran. Tech Interviews comment by Kiran Mandhadi 20. Can you can specify values for for variables in interfaces in c#? (In Java you can) Answer) NO. I tried this in VS.net and it gave me the following error: D:\VisualStudio\\Interface.cs(10): Interfaces cannot contain fields Tech Interviews comment by Kiran Mandhadi 21. #12 The .Net compiler does not accept a virtual private method which makes sense since a virtual private method makes no sense. Thanks, Laura Tech Interviews comment by Laura Hunt 22. Another response to #13: Since you constructors are not allowed in an interface, how would you be able to use an interface as a type parameter when the type parameter is constrained by new()? Tech Interviews comment by Ike 23. This is regarding question #5, if u cant access a member in derived class, then how do we say it is inherited.To my knowledge, the fundamental concept behind inheritance is representing the parent, if a child cont access then we can say its not inherited.Please correct me if am wrong. Tech Interviews comment by surendra 24. heres a question I was asked at an interview: What methods are called when a windows app is run and in what order are they called? 1. main 2. an instance of the form 3. form load

4. Initialize component 5. Dispose what am I forgetting? Tech Interviews comment by Andy 25. Another response to #13: Since you constructors are not allowed in an interface, how would you be able to use an interface as a type parameter when the type parameter is constrained by new()? You cant. But, if the generic class requires the type to have a default constructor, that means it plans on creating an instance of that type at some point; and since you cant create an instance of an interface, it wouldnt make any sense to use an interface as the type parameter. This is regarding question #5, if u cant access a member in derived class, then how do we say it is inherited.To my knowledge, the fundamental concept behind inheritance is representing the parent, if a child cont access then we can say its not inherited.Please correct me if am wrong. Technically, saying that a particular item is inherited means that it still exists in the derived class. In .NET this is always the case: if I have a private field in my base class, then when I instantiate my derived class, space is reserved on the heap for the private field, even though my derived class cannot access it directly. This is somewhat confusing, and makes for a bad interview question, because it is not clear whether the interviewer is asking if the private member still exists in the derived class, or if the derived class can access the private member. Tech Interviews comment by David 26. with regards to question #7: The default (parameterless) constructor is not implicitly canceled by C# simply by virtue of you writing one that requires a parameter. Though for ease of use you SHOULD implement default behavior and initialisations in the default constructor, unless parameters are absolutely required for initialisation. Which would only be necessary in the event of a lack of get/set properties for private/protected member variables. hope that makes sense. Jimbobob Tech Interviews comment by Jimbobob

27. oh yeah, and unless you intentionally erase the default consturctor in the code, itll stay there and stay functional. Tech Interviews comment by Jimbobob 28. On question 14, it should be noted that only overridden methods can be sealed Tech Interviews comment by Phil Curran ----------------

C# is one of the most visible aspects of Microsoft's .NET initiative. Developers commonly see the world through the lens of their language, and so C# can be their main aperture into .NET. Misconceptions abound, however. In this article, I'd like to address the confusions I hear most often about this new tool.

Which is better: C# or Java? The two languages have an awful lot in common, and so in some ways it's natural to try to choose a winner. The fact that each language is often viewed as the flagship of its campC# in Microsoft's .NET environment, with Java supported by everybody elsemakes the comparison especially attractive. But it's the wrong question. Not only is there no objective answer, it wouldn't matter if there were. To see why, realize that both languages are in fact embedded in a much larger matrix of technologies. Using C# requires using the .NET Framework, including the Common Language Runtime (CLR) and the .NET Framework class library. Similarly, using Java requires using a Java virtual machine and some set of Java packages. The choice implies an enterprise vendor decision as well: C# means Microsoft (today, at least), whereas Java means IBM or BEA or some other non-Microsoft choice. Deciding which of these paths to take based solely on the language is like buying a car because you like the radio. You can do it, but you'll be happier if you choose based on the whole package. Isn't C# just a copy of Java? In some ways, yes. The semantics of the CLR are quite Java-esque, and so any CLR-based language will have a good deal in common with Java. Creating a language that expresses those semantics in a syntax derived from C++ (for example, C#) is bound to result in something that looks a good deal like Java. Yet there are important features in C# that don't exist in Java. One good example is support for attributes, which allow a developer to easily control significant parts of her code's behavior. In .NET, attributes can be used to control which methods are exposed as SOAP-callable Web services, to set transaction requirements, and more. Still, if Microsoft had been free to make some changes to Java, my guess is that C# wouldn't exist today. Isn't C# the native language of .NET? Every language built on the .NET Framework must use the CLR. The CLR defines core language semantics, and so all of the languages built on it tend to have a great deal in common. The biggest choice a .NET compiler writer has is the syntax his language will use. Microsoft needed to provide a natural path to the .NET Framework for both C++ and Visual Basic developers, and so the company created C# and Visual Basic.NET. Yet the facilities these two languages offer are nearly identicalC# can do just a little bit moreand so neither is the "native" .NET language. There is no such thing. But won't most .NET developers eventually choose C# over Visual Basic.NET? No. Because the power of the two languages is so similar, the primary factor for developers migrating to the .NET world will probably be the syntax they prefer. Since many more developers use Visual Basic today than C++,

I expect that VB.NET will be the most popular choice. For the vast majority of VB developers who are fond of VB-style syntax, there's no reason to switch to C#. I believe that the dominant language for building Windows applications five years from now will still be Visual Basic.

Will we eventually see a .NET Framework-based version of Java as a competitor to C#? Apparently not. Microsoft will never offer a complete Java environment because Sun has essentially required that Java licensees implement all of Javasomething Microsoft will never do. (Why should it? Does anyone expect Sun to implement C#, VB.NET, and the .NET Framework?) And if a Java aficionado chooses to use a CLR-based Java compiler, such as the one included with Microsoft's JUMP for .NET technology, she's unlikely to be truly happy. Java implies a series of Java libraries and interfaces, such as Swing and Enterprise JavaBeans. The .NET Framework provides its own equivalent technologies, and so most of these won't be available. As a result, a developer using the Java language on the .NET Framework won't feel like she's working in a true Java environment because the familiar libraries won't be there.

C# is probably the most important new programming language since the advent of Java, and it will be used by many developers. But it may have gotten more attention than it deserves, if only because focusing on this new language tends to obscure the many other important innovations in the .NET Framework. Take it seriously, but don't think it's the main event in the new world of .NET.

C# Interview Questions
This is a list of questions I have gathered from other sources and created myself over a period of time from my experience, many of which I felt where incomplete or simply wrong. I have finally taken the time to go through each question and correct them to the best of my ability. However, please feel free to post feedback to challenge, improve, or suggest new questions. I want to thank those of you that have contributed quality questions and corrections thus far. There are some question in this list that I do not consider to be good questions for an interview. However, they do exist on other lists available on the Internet so I felt compelled to keep them easy access.

General Questions
1. Does C# support multiple-inheritance? No. 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. Whats 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. Whats 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. Whats 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. Whats 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. How can you sort the elements of the array in descending order? By calling Sort() and then Reverse() methods. 12. Whats the .NET collection class that allows an element to be accessed using a unique key?

HashTable. 13. What class is underneath the SortedList class? A sorted HashTable. 14. Will the finally block get executed if an exception has not occurred? Yes. 15. Whats 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 {}. 16. 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). 17. 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).

Class Questions
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. Whats 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 cant 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? Its 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 youre okay. To Do: Investigate 10. Whats 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.

Method and Property Questions


1. Whats 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.

Events and Delegates


1. Whats a delegate? A delegate object encapsulates a reference to a method. 2. Whats a multicast delegate? A delegate that has multiple handlers assigned to it. Each assigned handler (method) is called.

XML Documentation Questions


1. Is XML case-sensitive? Yes. 2. Whats the difference between // comments, /* */ comments and /// comments? Single-line comments, multi-line comments, and XML documentation comments. 3. How do you generate documentation from the C# file commented properly with a command-line compiler? Compile it with the /doc switch.

Debugging and Testing Questions


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. Whats 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.

ADO.NET and Database Questions


1. 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.

2. 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 its not as fastest and efficient as SqlServer.NET. 3. What is the wildcard character in SQL? Lets 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%. 4. 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 hasnt. 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. 5. What connections does Microsoft SQL Server support? Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and password). 6. 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. 7. What does the Initial Catalog parameter define in the connection string? The database name to connect to. 8. What does the Dispose method do with the connection object? Deletes it from the memory. To Do: answer better. The current answer is not entirely correct. 9. What is a pre-requisite for connection pooling? Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings. The connection string must be identical.

Assembly Questions
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.

Written by Riley Perry from Distributed Development OK here we go, the answers to the first 173. 1. Name 10 C# keywords. abstract, event, new, struct, explicit, null, base, extern, object, this 2. What is public accessibility? There are no access restrictions. 3. What is protected accessibility?

Access is restricted to types derived from the containing class. 4. What is internal accessibility? A member marked internal is only accessible from files within the same assembly. 5. What is protected internal accessibility? Access is restricted to types derived from the containing class or from files within the same assembly. 6. What is private accessibility? Access is restricted to within the containing class. 7. What is the default accessibility for a class? internal for a top level class, private for a nested one. 8. What is the default accessibility for members of an interface? public 9. What is the default accessibility for members of a struct? private 10. Can the members of an interface be private? No. 11. Methods must declare a return type, what is the keyword used when nothing is returned from the method? void 12. Class methods to should be marked with what keyword? static 13. Write some code using interfaces, virtual methods, and an abstract class. using System;

public interface Iexample1 { int MyMethod1(); } public interface Iexample2 { int MyMethod2(); } public abstract class ABSExample : Iexample1, Iexample2 { public ABSExample() { System.Console.WriteLine("ABSExample constructor"); } public int MyMethod1() { return 1; } public int MyMethod2() { return 2; } public abstract void MyABSMethod();

} public class VIRTExample : ABSExample { public VIRTExample() { System.Console.WriteLine("VIRTExample constructor"); } public override void MyABSMethod() { System.Console.WriteLine("Abstract method made concrete"); } public virtual void VIRTMethod1() { System.Console.WriteLine("VIRTMethod1 has NOT been overridden"); } public virtual void VIRTMethod2() { System.Console.WriteLine("VIRTMethod2 has NOT been overridden"); } } public class FinalClass : VIRTExample {

public override void VIRTMethod2() { System.Console.WriteLine("VIRTMethod2 has been overridden"); } }

14. A class can have many mains, how does this work? Only one of them is run, that is the one marked (public) static, e.g: public static void Main(string[] args) { // // TODO: Add code to start application here // } private void Main(string[] args, int i) { } 15. Does an object need to be made to run main? No 16. Write a hello world console application. using System; namespace Console1 { class Class1 { [STAThread] // No longer needed static void Main(string[] args) {

Console.WriteLine("Hello world"); } } } 17. What are the two return types for main? void and int 18. What is a reference parameter? Reference parameters reference the original object whereas value parameters make a local copy and do not affect the original. Some example code is shown: using System; namespace Console1 { class Class1 { static void Main(string[] args) { TestRef tr1 = new TestRef(); TestRef tr2 = new TestRef();

tr1.TestValue = "Original value"; tr2.TestValue = "Original value"; int tv1 = 1; int tv2 = 1; TestRefVal(ref tv1, tv2, ref tr1, tr2);

Console.WriteLine(tv1); Console.WriteLine(tv2); Console.WriteLine(tr1.TestValue); Console.WriteLine(tr2.TestValue); Console.ReadLine(); } static public void TestRefVal(ref int tv1Parm, int tv2Parm, ref TestRef tr1Parm, TestRef tr2Parm) { tv1Parm = 2; tv2Parm = 2; tr1Parm.TestValue = "New value"; tr2Parm.TestValue = "New value"; } } } class TestRef { public string TestValue; } The output for this is:

2 1 New value New value 19. What is an out parameter? An out parameter allows an instance of a parameter object to be made inside a method. Reference parameters must be initialised but out gives a reference to an uninstanciated object. 20. Write code to show how a method can accept a varying number of parameters. using System; namespace Console1 { class Class1 { static void Main(string[] args) { ParamsMethod(1,"example"); ParamsMethod(1,2,3,4); Console.ReadLine(); } static void ParamsMethod(params object[] list) { foreach (object o in list) {

Console.WriteLine(o.ToString()); } } } } 21. What is an overloaded method? An overloaded method has multiple signatures that are different. 22. What is recursion? Recursion is when a method calls itself. 23. What is a constructor? A constructor performs initialisation for an object (including the struct type) or class. 24. If I have a constructor with a parameter, do I need to explicitly create a default constructor? Yes 25. What is a destructor? A C# destuctor is not like a C++ destructor. It is actually an override for Finalize(). This is called when the garbage collector discovers that the object is unreachable. Finalize() is called before any memory is reclaimed. 26. Can you use access modifiers with destructors? No 27. What is a delegate? A delegate in C# is like a function pointer in C or C++. A delegate is a variable that calls a method indirectly, without knowing its name. Delegates can point to static or/and member functions. It is also possible to use a multicast delegate to point to multiple functions. 28. Write some code to use a delegate.

Member function with a parameter using System; namespace Console1 { class Class1 { delegate void myDelegate(int parameter1); static void Main(string[] args) { MyClass myInstance = new MyClass();

myDelegate d = new myDelegate(myInstance.AMethod);

d(1); // <--- Calling function without knowing its name.

Test2(d); Console.ReadLine(); } static void Test2(myDelegate d) { d(2); // <--- Calling function without knowing its name. } }

class MyClass { public void AMethod(int param1) { Console.WriteLine(param1); } } } Multicast delegate calling static and member functions using System; namespace Console1 { class Class1 { delegate void myDelegate(int parameter1); static void AStaticMethod(int param1) { Console.WriteLine(param1); } static void Main(string[] args) { MyClass myInstance = new MyClass();

myDelegate d = null; d += new myDelegate(myInstance.AMethod); d += new myDelegate(AStaticMethod); d(1); //both functions will be run. Console.ReadLine(); } } class MyClass { public void AMethod(int param1) { Console.WriteLine(param1); } } } 29. What is a delegate useful for? The main reason we use delegates is for use in event driven programming. 30. What is an event? See 32 31. Are events synchronous of asynchronous? Asynchronous 32. Events use a publisher/subscriber model. What is that? Objects publish events to which other applications subscribe. When the publisher raises an event all subscribers to that event are notified.

33. Can a subscriber subscribe to more than one publisher? Yes, also - here's some code for a publisher with multiple subscribers. using System; namespace Console1 { class Class1 { delegate void myDelegate(int parameter1); static event myDelegate myEvent;

static void AStaticMethod(int param1) { Console.WriteLine(param1); } static void Main(string[] args) { MyClass myInstance = new MyClass();

myEvent += new myDelegate(myInstance.AMethod); myEvent += new myDelegate(AStaticMethod); myEvent(1); //both functions will be run. Console.ReadLine(); }

} class MyClass { public void AMethod(int param1) { Console.WriteLine(param1); } } } Another example: using System; using System.Threading; namespace EventExample { public class Clock { public delegate void TwoSecondsPassedHandler(object clockInstance, TimeEventArgs time); //The clock publishes an event that others subscribe to public event TwoSecondsPassedHandler TwoSecondsPassed;

public void Start() { while(true)

{ Thread.Sleep(2000);

//Raise event TwoSecondsPassed(this, new TimeEventArgs(1)); } } } public class TimeEventArgs : EventArgs { public TimeEventArgs(int second) { seconds += second; instanceSeconds = seconds; } private static int seconds; public int instanceSeconds; } public class MainClass { static void Main(string[] args) { Clock cl = new Clock();

// add some subscribers cl.TwoSecondsPassed += new Clock.TwoSecondsPassedHandler(Subscriber1); cl.TwoSecondsPassed += new Clock.TwoSecondsPassedHandler(Subscriber2); cl.Start(); Console.ReadLine(); } public static void Subscriber1(object clockInstance, TimeEventArgs time) { Console.WriteLine("Subscriber1:" + time.instanceSeconds); } public static void Subscriber2(object clockInstance, TimeEventArgs time) { Console.WriteLine("Subscriber2:" + time.instanceSeconds); } } } 34. What is a value type and a reference type? A reference type is known by a reference to a memory location on the heap. A value type is directly stored in a memory location on the stack. A reference type is essentially a pointer, dereferencing the pointer takes more time than directly accessing the direct memory location of a value type. 35. Name 5 built in types.

Bool, char, int, byte, double 36. string is an alias for what? System.String 37. Is string Unicode, ASCII, or something else? Unicode 38. Strings are immutable, what does this mean? Any changes to that string are in fact copies. 39. Name a few string properties. trim, tolower, toupper, concat, copy, insert, equals, compare. 40. What is boxing and unboxing? Converting a value type (stack->heap) to a reference type (heap->stack), and vise-versa. 41. Write some code to box and unbox a value type. // Boxing int i = 4; object o = i; // Unboxing i = (int) o; 42. What is a heap and a stack? There are 2 kinds of heap 1: a chunk of memory where data is stored and 2: a tree based data structure. When we talk about the heap and the stack we mean the first kind of heap. The stack is a LIFO data structure that stores variables and flow control information. Typically each thread will have its own stack. 43. What is a pointer? A pointer is a reference to a memory address.

44. What does new do in terms of objects? Initializes an object. 45. How do you dereference an object? Set it equal to null. 46. In terms of references, how do == and != (not overridden) work? They check to see if the references both point to the same object. 47. What is a struct? Unlike in C++ a struct is not a class it is a value type with certain restrictions. It is usually best to use a struct to represent simple entities with a few variables. Like a Point for example which contains variables x and y. 48. Describe 5 numeric value types ranges. sbyte -128 to 127, byte 0 255, short -32,768 to 32,767, int -2,147,483,648 to 2,147,483,647, ulong 0 to 18,446,744,073,709,551,615 49. What is the default value for a bool? false 50. Write code for an enumeration. public enum animals {Dog=1,Cat,Bear}; 51. Write code for a case statement. switch (n) { case 1: x=1; break; case 2: x=2;

break; default: goto case 1; } 52. Is a struct stored on the heap or stack? Stack 53. Can a struct have methods? Yes 54. What is checked { } and unchecked { }? By default C# does not check for overflow (unless using constants), we can use checked to raise an exception. E.g.: static short x = 32767; // Max short value static short y = 32767; // Using a checked expression public static int myMethodCh() { int z = 0; try { z = checked((short)(x + y)); //z = (short)(x + y); } catch (System.OverflowException e) {

System.Console.WriteLine(e.ToString()); } return z; // Throws the exception OverflowException } This code will raise an exception, if we remove unchecked as in: //z = checked((short)(x + y)); z = (short)(x + y); Then the cast will raise no overflow exception and z will be assigned 2. unchecked can be used in the opposite way, to say avoid compile time errors with constanst overflow. E.g. the following will cause a compiler error: const short x = 32767; // Max short value const short y = 32767; public static int myMethodUnch() { int z = (short)(x + y); return z; // Returns -2 } The following will not: const short x = 32767; // Max short value const short y = 32767; public static int myMethodUnch() { int z = unchecked((short)(x + y)); return z; // Returns -2

} 55. Can C# have global overflow checking? Yes 56. What is explicit vs. implicit conversion? When converting from a smaller numeric type into a larger one the cast is implicit. An example of when an explicit cast is needed is when a value may be truncated. 57. Give examples of both of the above. // Implicit short shrt = 400; int intgr = shrt; // Explicit shrt = (short) intgr; 58. Can assignment operators be overloaded directly? No 59. What do operators is and as do? as acts is like a cast but returns a null on conversion failure. Is compares an object to a type and returns a boolean. 60. What is the difference between the new operator and modifier? The new operator creates an instance of a class whereas the new modifier is used to declare a method with the same name as a method in one of the parent classes. 61. Explain sizeof and typeof. typeof obtains the System.Type object for a type and sizeof obtains the size of a type. 62. What doe the stackalloc operator do?

Allocate a block of memory on the stack (used in unsafe mode). 63. Contrast ++count vs. count++. Some operators have temporal properties depending on their placement. E.g. double x; x = 2; Console.Write(++x); x = 2; Console.Write(x++); Console.Write(x); Returns 323 64. What are the names of the three types of operators? Unary, binary, and conversion. 65. An operator declaration must include a public and static modifier, can it have other modifiers? No 66. Can operator parameters be reference parameters? No 67. Describe an operator from each of these categories: Arithmetic: + Logical (boolean and bitwise): & String concatenation: + Increment, decrement: ++ Shift: >> Relational: == Assignment: = Member access: .

Indexing: [] Cast: () Conditional: ?: Delegate concatenation and removal: + Object creation: new Type information: as Overflow exception control: checked Indirection and Address: * 68. What does operator order of precedence mean? Certain operators are evaluated before others. Brackets help to avoid confusion. 69. What is special about the declaration of relational operators? Relational operators must be declared in pairs. 70. Write some code to overload an operator. class TempleCompare { public int templeCompareID; public int templeValue; public static bool operator == (TempleCompare x, TempleCompare y) { return (x.templeValue == y.templeValue); } public static bool operator != (TempleCompare x, TempleCompare y) { return !(x == y); } public override bool Equals(object o) { // check types match if (o == null || GetType()!= o.GetType()) return false; TempleCompare t = (templeCompare) o; return (this.templeCompareID == t.templeCompareID) && (this.templeValue == t.templeValue);

} public override int GetHashCode() { return templeCompareID; } } 71. What operators cannot be overloaded? =, ., ?:, ->, new, is, sizeof, typeof 72. What is an exception? A runtime error. 73. Can C# have multiple catch blocks? Yes 74. Can break exit a finally block? No 75. Can Continue exit a finally block? No 76. Write some trycatchfinally code. // try-catch-finally using System; public class TCFClass { public static void Main () { try { throw new NullReferenceException();

} catch(NullReferenceException e) { Console.WriteLine("{0} exception 1.", e); } catch { Console.WriteLine("exception 2."); } finally { Console.WriteLine("finally block."); } } } 77. What are expression and declaration statements? Expression produces a value e.g. blah = 0 Declaration e.g. int blah;

78. A block contains a statement list {s1;s2;} what is an empty statement list? {;} 79. Write some if else if code. int n=4; if (n==1)

Console.WriteLine("n=1"); else if (n==2) Console.WriteLine("n=2"); else if (n==3) Console.WriteLine("n=3"); else Console.WriteLine("n>3"); 80. What is a dangling else? if (n>0) if (n2>0) Console.Write("Dangling Else") else 81. Is switch case sensitive? Yes 82. Write some code for a for loop for (int i = 1; i <= 5; i++) Console.WriteLine(i); 83. Can you increment multiple variables in a for loop control? Yes e.g. for (int i = 1; j = 2;i <= 5 ;i++ ;j=j+2) 84. Write some code for a while loop. int n = 1; while (n < 6) {

Console.WriteLine("Current value of n is {0}", n); n++; } 85. Write some code for do while. int x; int y = 0; do { x = y++; Console.WriteLine(x); } while(y < 5); 86. Write some code that declares an array on ints, assigns the values: 0,1,2,5,7,8,11 to that array and use a foreach to do something with those values. int x = 0, y = 0; int[] arr = new int [] {0,1,2}; foreach (int i in arr) { if (i%2 == 0) x++; else y++; }

87. Write some code for a custom collection class. using System; using System.Collections; public class Items : IEnumerable { private string[] contents; public Items(string[] contents) { this.contents = contents; } public IEnumerator GetEnumerator() { return new ItemsEnumerator(this); } private class ItemsEnumerator : IEnumerator { private int location = -1; private Items i; public ItemsEnumerator(Items i) { this.i = i; } public bool MoveNext()

{ if (location < i.contents.Length - 1) { location++; return true; } else { return false; } } public void Reset() { location = -1; } public object Current { get { return i.contents[location]; } } }

static void Main() { // Test string[] myArray = {"a","b","c"}; Items items = new Items(myArray); foreach (string item in items) { Console.WriteLine(item); } Console.ReadLine(); } } 88. Describe Jump statements: break, continue, and goto. Break terminates a loop or switch. Continue jumps to the next iteration of an enclosing iteration statement. Goto jumps to a labelled statement. 89. How do you declare a constant? public const int c1 = 5; 90. What is the default index of an array? 0 91. What is array rank? The dimension of the array. 92. Can you resize an array at runtime? No 93. Does the size of an array need to be defined at compile time.

No 94. Write some code to implement a multidimensional array. int[,] b = {{0, 1}, {2, 3}, {4, 5}, {6, 7}, {8, 9}}; 95. Write some code to implement a jagged array. // Declare the array of two elements: int[][] myArray = new int[2][]; // Initialize the elements: myArray[0] = new int[5] {1,3,5,7,9}; myArray[1] = new int[4] {2,4,6,8}; 96. What is an ArrayList? A data structure from System.Collections that can resize itself. 97. Can an ArrayList be ReadOnly? Yes 98. Write some code that uses an ArrayList. ArrayList list = new ArrayList(); list.Add("Hello"); list.Add("World"); 99. Write some code to implement an indexer. using System; namespace Console1 { class Class1 {

static void Main(string[] args) { MyIndexableClass m = new MyIndexableClass(); Console.WriteLine(m[0]); Console.WriteLine(m[1]); Console.WriteLine(m[2]); Console.ReadLine(); } } class MyIndexableClass { private string []myData = {"one","two","three"}; public string this [int i] { get { return myData[i]; } set { myData[i] = value; } }

} } 100. Yes 101. Yes 102. What happens if you make a property static? Can properties hide base class members of the same name? Can properties have an access modifier?

They become class properties. 103. Can a property be a ref or out parameter?

A property is not classified as a variable it cant be ref or out parameter. 104. Write some code to declare and use properties.

// instance public string InstancePr { get { return a; } set { a = value; } }

//read-only static public static int ClassPr { get { return b; } } 105. What is an accessor?

An accessor contains executable statements associated with getting or setting properties. 106. Yes 107. What is early and late binding? Can an interface have properties?

Late binding is using System.object instead of explicitly declaring a class (which is early binding). 108. What is polymorphism

Polymorphism is the ability to implement the same operation many times. Each derived method implements the operation inherited from the base class in its own way. 109. What is a nested class?

A class declare within a class. 110. What is a namespace?

A namespace declares a scope which is useful for organizing code and to distinguish one type from another. 111. Can nested classes use any of the 5 types of accessibility?

Yes 112. Yes 113. object is an alias for what? Can base constructors can be private?

System.Object 114. What is reflection?

Reflection allows us to analyze an assemblys metadata and it gives us a mechanism to do late binding. 115. What namespace would you use for reflection?

System.Reflection 116. What does this do? Public Foo() : this(12, 0, 0)

Calls another constructor in the list 117. Do local values get garbage collected?

They die when they are pulled off the stack (go out of scope). 118. No 119. Describe garbage collection (in simple terms). Is object destruction deterministic?

Garbage collection eliminates uneeded objects. 1. the new statement allocates memory for an object on the heap. 2. When no objects reference the object it may be removed from the heap (this is a non deterministic process). 3. Finalize is called just before the memory is released. 120. What is the using statement for?

The using statement defines a scope at the end of which an object will be disposed. 121. How do you refer to a member in the base class?

To refer to a member in the base class use:return base.NameOfMethod(). 122. No 123. No 124. All classes derive from what? Does C# supports multiple inheritance? Can you derive from a struct?

System.Object 125. Is constructor or destructor inheritance explicit or implicit? What does this mean? Constructor or destructor inheritance is explicit. Public Extended : base() this is called the constructor initializer. 126. No 127. Does C# have friendship? Can different assemblies share internal access?

Not before C# 2.0 128. Yes 129. In terms of constructors, what is the difference between: public MyDerived() : base() an public MyDerived() in a child class? Nothing 130. Yes 131. this 132. Can you have nested namespaces? What keyword would you use for scope name clashes? Can abstract methods override virtual methods? Can you inherit from multiple interfaces?

Yes 133. What are attributes?

Attributes are declarative tags which can be used to mark certain entities (like methods for example). 134. Name 3 categories of predefined attributes.

COM Interop, Transaction, Visual Designer Component Builder 135. What are the 2 global attributes.

assembly and module. 136. Why would you mark something as Serializable?

To show that the marked type can be serialized. 137. Write code to define and use your own custom attribute.

(From MSDN) // cs_attributes_retr.cs using System; [AttributeUsage(AttributeTargets.Class|AttributeTargets.Struct, AllowMultiple=true)] public class Author : Attribute { public Author(string name) { this.name = name; version = 1.0; } public double version; string name;

public string GetName() { return name; } } 138. List some custom attribute scopes and possible targets.

Assembly assembly Class type Delegate - type, return 139. #if #else #elif #endif #define #undef #warning #error #line #region #endregion 140. What is a thread? List some compiler directives?

A thread is a the entity within a process that Windows schedules for execution. A thread has:

The contents of a set of CPU registers representing the state of the processor. 2 stacks, 1 for the thread to use in kernel mode, and 1 for user mode. Private storage called Thread Local Storage for use by subsystems, runtime libraries, and DLLs. A thread ID.

Threads sometimes have their own security context. 141. Do you spin off or spawn a thread?

Spin off 142. What is the volatile keyword used for?

It indicates a field can be modified by an external entity (thread, OS, etc.). 143. Write code to use threading and the lock keyword.

using System; using System.Threading; namespace ConsoleApplication4 { class Class1 { [STAThread] static void Main(string[] args) { ThreadClass tc1 = new ThreadClass(1); ThreadClass tc2 = new ThreadClass(2); Thread oT1 = new Thread(new ThreadStart(tc1.ThreadMethod)); Thread oT2 = new Thread(new ThreadStart(tc2.ThreadMethod));

oT1.Start(); oT2.Start(); Console.ReadLine(); } } class ThreadClass { private static object lockValue = "dummy"; public int threadNumber; public ThreadClass(int threadNumber) { this.threadNumber = threadNumber; } public void ThreadMethod() { for (;;) { lock(lockValue) { Console.WriteLine(threadNumber + " working"); Thread.Sleep(1000); } }

} } } 144. What is Monitor?

Monitor is a class that has various functions for thread synchronization. 145. What is a semaphore?

A resource management, synchronization, and locking tool. 146. What mechanisms does C# have for the readers, writers problem?

System.Threading.ReaderWriterLock which has methods AcquireReaderLock, ReleaseReaderLock, AcquireWriterLock, and ReleaseWriterLock 147. What is Mutex?

A Mutex object is used to guarantee only one thread can access a critical resource an any one time. 148. What is an assembly?

Assemblies contain logical units of code in MSIL, metadata, and usually a manifest. Assemblies can be signed and the can dome in the form of a DLL or EXE. 149. What is a DLL?

A set of callable functions, which can be dynamically loaded. 150. What is an assembly identity?

Assembly identity is name, version number, and optional culture, and optional public key to guarantee uniqueness. 151. What does the assembly manifest contain?

Assembly manifest lists all names of public types and resources and their locations in the assembly. 152. What is IDLASM used for?

Use IDLASM to see assembly internals. It disassembles into MSIL. 153. Where are private assemblies stored?

Same folder as exe 154. Where are shared assemblies stored?

The GAC 155. What is DLL hell?

DLLs, VBX or OCX files being unavailable or in the wrong versions. Applicatioins using say these older DLLs expect some behaviour which is not present. 156. In terms of assemblies, what is side-by-side execution?

An app can be configured to use different versions of an assembly simultaneously. 157. Name and describe 5 different documentation tags.

/// <value></value> /// <example></example> /// <exception cref=""></exception> /// <include file='' path='[@name=""]'/> /// <param name="args"></param> /// <paramref name=""/> /// <permission cref=""></permission> /// <remarks> /// </remarks> /// <summary> /// <c></c> /// <code></code>

/// <list type=""></list> /// <see cref=""/> /// <seealso cref=""/> /// </summary> 158. What is unsafe code?

Unsafe code bypasses type safety and memory management. 159. What does the fixed statement do?

Prevents relocation of a variable by GC. 160. How would you read and write using the console?

Console.Write, Console.WriteLine, Console.Readline 161. Give examples of hex, currency, and fixed point console formatting.

Console.Write("{0:X}", 250); FA Console.Write("{0:C}", 2.5); $2.50 Console.Write("{0:F2}", 25); 25.00 162. Given part of a stack trace: aspnet.debugging.BadForm.Page_Load(Object sender, EventArgs e) +34. What does the +34 mean? It is an actual offset (at the assembly language level) not an offset into the IL instructions. 163. Yes 164. How can you implement a mutable string? Are value types are slower to pass as method parameters?

System.Text.StringBuilder 165. What is a thread pool?

A thread pool is a means by which to control a number of threads simultaneously. Thread pools give us thread reuse, rather than creating a new thread every time. 166. From http://msdn.microsoft.com/msdnmag/issues/02/09/SecurityinNET/default.as px Unlike the old principal-based security, the CLR enforces security policy based on where code is coming from rather than who the user is. This model, called code access security, makes sense in today's environment because so much code is installed over the Internet and even a trusted user doesn't know when that code is safe. 167. Whats the difference between camel and pascal casing? Describe the CLR security model.

PascalCasing, camelCasing 168. From http://www.dictionary.net/marshalling The process of packing one or more items of data into a message buffer, prior to transmitting that message buffer over a communication channel. The packing process not only collects together values which may be stored in nonconsecutive memory locations but also converts data of different types into a standard representation agreed with the recipient of the message. 169. What is inlining? What does marshalling mean?

From (Google web defintions) In-line expansion or inlining for short is a compiler optimization which "expands" a function call site into the actual implementation of the function which is called, rather than each call transferring control to a common piece of code. This reduces overhead associated with the function call, which is especially important for small and frequently called functions, and it helps call-site-specific compiler optimizations, especially constant propagation. 170. List the differences in C# 2.0.

Generics Iterators Partial class definitions Nullable Types Anonymous methods :: operator Static classes static class members Extern keyword Accessor accessibility Covariance and Contravariance Fixed size buffers Fixed assemblies #pragma warning What are design patterns?

171. From

http://www.dofactory.com/Patterns/Patterns.aspx Design patterns are recurring solutions to software design problems you find again and again in real-world application development. 172. From http://www.dofactory.com/Patterns/Patterns.aspx Creational Patterns Abstract Factory Creates an instance of several families of classes Describe some common design patterns.

Builder Separates object construction from its representation Factory Method Creates an instance of several derived classes Prototype A fully initialized instance to be copied or cloned Singleton A class of which only a single instance can exist Structural Patterns Adapter Match interfaces of different classes Bridge Separates an objects interface from its implementation Composite A tree structure of simple and composite objects Decorator Add responsibilities to objects dynamically Faade A single class that represents an entire subsystem Flyweight A fine-grained instance used for efficient sharing Proxy An object representing another object Behavioral Patterns Chain of Resp. A way of passing a request between a chain of objects Command Encapsulate a command request as an object Interpreter A way to include language elements in a program Iterator Sequentially access the elements of a collection Mediator Defines simplified communication between classes Memento Capture and restore an object's internal state Observer A way of notifying change to a number of classes State Alter an object's behavior when its state changes Strategy Encapsulates an algorithm inside a class Template Method Defer the exact steps of an algorithm to a subclass

Visitor Defines a new operation to a class without change 173. From http://www.developer.com/design/article.php/1553851

What are the different diagrams in UML? What are they used for?

Use case diagram: The use case diagram is used to identify the primary elements and processes that form the system. The primary elements are termed as "actors" and the processes are called "use cases." The use case diagram shows which actors interact with each use case. Class diagram: The class diagram is used to refine the use case diagram and define a detailed design of the system. The class diagram classifies the actors defined in the use case diagram into a set of interrelated classes. The relationship or association between the classes can be either an "is-a" or "has-a" relationship. Each class in the class diagram may be capable of providing certain functionalities. These functionalities provided by the class are termed "methods" of the class. Apart from this, each class may have certain "attributes" that uniquely identify the class. Object diagram: The object diagram is a special kind of class diagram. An object is an instance of a class. This essentially means that an object represents the state of a class at a given point of time while the system is running. The object diagram captures the state of different classes in the system and their relationships or associations at a given point of time. State diagram: A state diagram, as the name suggests, represents the different states that objects in the system undergo during their life cycle. Objects in the system change states in response to events. In addition to this, a state diagram also captures the transition of the object's state from an initial state to a final state in response to events affecting the system. Activity diagram: The process flows in the system are captured in the activity diagram. Similar to a state diagram, an activity diagram also consists of activities, actions, transitions, initial and final states, and guard conditions. Sequence diagram: A sequence diagram represents the interaction between different objects in the system. The important aspect of a sequence diagram is that it is time-ordered. This means that the exact sequence of the interactions between the objects is represented step by step. Different objects in the sequence diagram interact with each other by passing "messages". Collaboration diagram: A collaboration diagram groups together the interactions between different objects. The interactions are listed as numbered interactions that help to trace the sequence of the interactions.

The collaboration diagram helps to identify all the possible interactions that each object has with other objects. Component diagram: The component diagram represents the high-level parts that make up the system. This diagram depicts, at a high level, what components form part of the system and how they are interrelated. A component diagram depicts the components culled after the system has undergone the development or construction phase. Deployment diagram: The deployment diagram captures the configuration of the runtime elements of the application. This diagram is by far most useful when a system is built and ready to be deployed.

C# Interview Questions (http://blogs.crsw.com/mark/articles/252.aspx)


This is a list of questions I have gathered from other sources and created myself over a period of time from my experience, many of which I felt where incomplete or simply wrong. I have finally taken the time to go through each question and correct them to the best of my ability. However, please feel free to post feedback to challenge, improve, or suggest new questions. I want to thank those of you that have contributed quality questions and corrections thus far. There are some question in this list that I do not consider to be good questions for an interview. However, they do exist on other lists available on the Internet so I felt compelled to keep them easy access.

General Questions
1. Does C# support multiple-inheritance? No. 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. Whats 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. Whats 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. Whats 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. Whats 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. How can you sort the elements of the array in descending order? By calling Sort() and then Reverse() methods. 12. Whats the .NET collection class that allows an element to be accessed using a unique key? HashTable. 13. What class is underneath the SortedList class? A sorted HashTable. 14. Will the finally block get executed if an exception has not occurred? Yes. 15. Whats 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 {}.

16. 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). 17. 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).

Class Questions
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. Whats 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 cant 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?

Its 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 youre okay. To Do: Investigate 10. Whats 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.

Method and Property Questions


1. Whats 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.

Events and Delegates


1. Whats a delegate? A delegate object encapsulates a reference to a method. 2. Whats a multicast delegate? A delegate that has multiple handlers assigned to it. Each assigned handler (method) is called.

XML Documentation Questions


1. Is XML case-sensitive? Yes. 2. Whats the difference between // comments, /* */ comments and /// comments? Single-line comments, multi-line comments, and XML documentation comments. 3. How do you generate documentation from the C# file commented properly with a command-line compiler? Compile it with the /doc switch.

Debugging and Testing Questions


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. Whats 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.

ADO.NET and Database Questions


1. 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.

2. 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 its not as fastest and efficient as SqlServer.NET. 3. What is the wildcard character in SQL? Lets 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%. 4. 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 hasnt. 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. 5. What connections does Microsoft SQL Server support? Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and password). 6. 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. 7. What does the Initial Catalog parameter define in the connection string? The database name to connect to. 8. What does the Dispose method do with the connection object? Deletes it from the memory. To Do: answer better. The current answer is not entirely correct. 9. What is a pre-requisite for connection pooling? Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings. The connection string must be identical.

Assembly Questions
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.

(http://www.techinterviews.com/?p=57) Whats the advantage of using System.Text.StringBuilder over System.String? StringBuilder is more efficient in the cases, where a lot of manipulation is done to the text. Strings are immutable, so each time its being operated on, a new instance is created. Can you store multiple data types in System.Array? No. Whats 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 can you sort the elements of the array in descending order? By calling Sort() and then Reverse() methods. Whats the .NET datatype that allows the retrieval of data by a unique key? HashTable. Whats class SortedList underneath? A sorted HashTable. Will finally block get executed if the exception had not occurred? Yes. Whats the C# equivalent of C++ catch (), which was a catch-all statement for 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 {}. Can multiple catch blocks be executed? No, once the proper catch code fires off, the control is transferred to the finally block (if there are any), and then whatever follows the finally block. Why is it a bad idea to throw your own exceptions? 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. Whats a delegate? A delegate object encapsulates a reference to a method. In C++ they were referred to as function pointers.

Whats a multicast delegate? Its a delegate that points to and eventually fires off several methods. Hows 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. Whats 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. What namespaces are necessary to create a localized application? System.Globalization, System.Resources. Whats the difference between // comments, /* */ comments and /// comments? Single-line, multi-line and XML documentation comments. How do you generate documentation from the C# file commented properly with a command-line compiler? Compile it with a /doc switch. Whats the difference between <c> and <code> XML documentation tag? Single line code example and multiple-line code example. Is XML case-sensitive? Yes, so <Student> and <student> are different elements. What debugging tools come with the .NET SDK? CorDBG command-line debugger, and DbgCLR graphic debugger. Visual Studio .NET uses the DbgCLR. To use CorDbg, you must compile the original C# file using the /debug switch. What does the This window show in the debugger? It points to the object thats pointed to by this reference. Objects instance data is shown. What does assert() do? In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true. Whats 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. 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. 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? Positive test cases (correct data, correct output), negative test cases (broken or missing data, proper handling), 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. Explain the three services model (three-tier application). Presentation (UI), business (logic and underlying code) and data (from storage or other sources).

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, but its a .NET layer on top of OLE layer, so not the fastest thing in the world. ODBC.NET is a deprecated layer provided for backward compatibility to ODBC engines. Whats the role of the DataReader class in ADO.NET connections? It returns a read-only dataset from the data source when the command is executed. What is the wildcard character in SQL? Lets 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. 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 hasnt), 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). What connections does Microsoft SQL Server support? Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and passwords). 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. Why would you use untrusted verificaion? Web Services might use it, as well as non-Windows applications. What does the parameter Initial Catalog define inside Connection String? The database name to connect to. Whats the data provider name to connect to Access database? Microsoft.Access. What does Dispose method do with the connection object? Deletes it from the memory. What is a pre-requisite for connection pooling? Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings.

Contents
2. C# Interview Questions..........................................................................1 C# interview questions..............................................................................1 28 Comments ............................................................................................ 4 C# Interview Questions............................................................................12

Member function with a parameter................................................................29 Multicast delegate calling static and member functions.............................30 From .............................................................................................................. 63 From............................................................................................................... 63 From............................................................................................................... 64 From............................................................................................................... 64 Structural Patterns .................................................................................. 65 Behavioral Patterns .................................................................................65 C# Interview Questions............................................................................67 (http://blogs.crsw.com/mark/articles/252.aspx).......................................67 Contents......................................................................................................... 76 .NET Framework............................................................................................. 86 What is CTS................................................................................................. 86 What is a CLS............................................................................................. 86 What is a Assembly..................................................................................... 86 What is the difference between a namespace and an assembly name?.....87 What is Manifest.......................................................................................... 87 What is GAC................................................................................................ 87 What is concept of strong names................................................................87 How to add and remove a assembly from GAC...........................................87 What is an application domain....................................................................87 Structures:...................................................................................................... 88 Classes:.......................................................................................................... 88 Class Modifier Table ................................................................................... 88 Member Accessibility..................................................................................88 Member Modifiers........................................................................................ 89 Instance Constructors:................................................................................... 89 Static Constructors:........................................................................................ 89 Implement a Singleton using Static Constructor:...........................................90 Nullable Types:............................................................................................... 90 Identity versus Equivalence........................................................................91 System.Object............................................................................................. 91 Object.Equals Method.................................................................................91

Object.ReferenceEquals Method.................................................................91 Collections...................................................................................................... 91 Generics:........................................................................................................ 91 Generic Types............................................................................................. 92 Delegates and Events.................................................................................... 92 Covariance and contravariance......................................................................93 Inheritance versus composition: Which one should you choose?...................93 Delayed Signing............................................................................................. 94 Casting Operators.......................................................................................... 94 Implementing a C# Collection........................................................................94 Implementing Finalize and Dispose to Clean Up Unmanaged Resources.......94 Finalize........................................................................................................... 95 Dispose........................................................................................................... 96 What size is a .NET object?............................................................................. 97 Can you prevent your class from being inherited by another class................97 Passing a Variable Number of Parameters to a Method.................................97 Dump Method Names using Reflection:.........................................................97 Dynamic Invocation using Relection:.............................................................98 Indexers......................................................................................................... 98 Reflection:...................................................................................................... 98 Obtaining a Type Object.............................................................................. 98 Loading Assemblies..................................................................................... 99 Browsing Type Information.........................................................................99 Checked and UnChecked Operators............................................................99 Difference between ReadOnly field and constant field...............................99 Advantage of anonymous delegate.............................................................99 Can a structure have default constructor..................................................100 What is a satellite assembly......................................................................100 What is an appdomain?............................................................................. 100 What is boxing and Unboxing. ..................................................................100 What happens when a value type is added to an arraylist........................100 What is serialization..................................................................................100 Difference between .................................................................................. 100

Write a function in C# that will take one input parameter and return true if given input type is int or long else false?..................................................100 What is static class? And how it is different from normal class?..............100 What is the difference between ref and out keywords in C#?..................100 What is delegate? What is the difference between delegate and event? 101 What is polymorphism? What is the importance of new and override operators (key words) in terms of Polymorphism?....................................101 What is the difference between Array and Dictionary? When to use what? .................................................................................................................. 101 What is the purpose of GAC? What are the prerequisites for putting a dll in GAC?......................................................................................................... 101 What is the difference between "overload" and "override" in C#?..........101 Memory Management:.................................................................................101 Creational Patterns ...................................................................................... 101 Abstract Factory - Creates an instance of several families of classes ....101 Builder - Separates object construction from its representation ..........101 Factory Method - Creates an instance of several derived classes ..........101 Prototype - A fully initialized instance to be copied or cloned ..............101 Singleton - A class of which only a single instance can exist ...............102 Structural Patterns ...................................................................................... 102 Adapter - Match interfaces of different classes ....................................102 Bridge - Separates an objects interface from its implementation .......102 Composite - A tree structure of simple and composite objects ............102 Decorator - Add responsibilities to objects dynamically .......................102 Faade - A single class that represents an entire subsystem ...............102 Flyweight - A fine-grained instance used for efficient sharing ..............102 Proxy - An object representing another object .....................................102 Behavioral Patterns ..................................................................................... 102 Chain of Responsibility - A way of passing a request between a chain of objects ..................................................................................................... 102 Command - Encapsulate a command request as an object .................102 Interpreter - A way to include language elements in a program ..........103 Iterator - Sequentially access the elements of a collection ..................103 Mediator - Defines simplified communication between classes ...........103

Memento - Capture and restore an object's internal state ...................103 Observer - A way of notifying change to a number of classes ..............103 State - Alter an object's behavior when its state changes ....................103 Strategy - Encapsulates an algorithm inside a class ............................103 Template Method - Defer the exact steps of an algorithm to a subclass .................................................................................................................. 103 Visitor - Defines a new operation to a class without change.................103 Which one of the following tools is used to view the metadata information contained in a .NET assembly?.....................................................................121 1. What is the lifespan for items stored in ViewState?.................................122 What si the difference between interface and abstractclass........................122 Maximum How Many Non-Clustor Index Created per Table?.......................123 Data in ViewState is in Which Form??..........................................................123 How many types of polymorphism in C#.....................................................123 What are the two methods to move from one webform to another webform ..................................................................................................................... 124 What are Managed Providers in .NET..........................................................124 Is multiple inheritance supported by c#?.....................................................124 what is the command for listing all permission sets using caspol...............125 which command for listing all code groups using caspol..............................125 what are three policy in configuration files..................................................125 WSDL is short form for................................................................................ 125 Which transport protocol is used to call webservies?...................................126 The process in which a web page sends data back to the same page on the server is called?........................................................................................... 126 Where is an asp.net form always submitted?...............................................126 What data type does the RangeValidator control support?..........................127 Name the namespace for working with Data specific to IBM DB2?..............127 what is the command for building the batch files in .Net Framework..........127 What is diffrence between Int16,Int32,Int64 in C# ?...................................128 how many types of inheritance is supported by c#.....................................128 How many types of JIT in present in ,Net .....................................................128 I have triggers, views, functions, stored Procedures for a table when I am dropping that table what are the objects deleted?.....................129

If you have two DLL files, how would you differentiate that which DLL is belong to .Net .............................................................................................. 129 In how many ways we can pass parameters through function call in c#.net?......................................................................................................... 129 Reflection reads information from the information store of assemblies Reflection reads information from the information store of assemblies does system .reflection store information about assemblies.......................130 The default type of enum is integer and has a default value 1....................130 Unboxing of a null reference type will return a null......................................130 what is the difference between CLS and CTS?.............................................131 if the code is like this; byte a, b, c; a = 255; b = 122; c = (byte)(a & b); what will be the value of C?.........................................................................131 Which of the following contains web application setup strings?...................131 Difference between Override and Overload?................................................132 does c# support templates..........................................................................132 What is the advantage of materialised View?..............................................133 OLTP Stands for?.......................................................................................... 133 What's the maximum size of a row?.............................................................134 RAID stands for............................................................................................. 134 You ASP.NET application manages order entry data by using a DataSet object named orderEntry. The orderEntry object includes two DataTable objects named orderNames and OrderDetails. A ForeignKeyConstraint object named orderDetailsKey is defined between the two DataTable objects. You attempt to delete a row in orderNames while there are related rows in OrderDetails, and an exception is generated. What is the most likely cause of the problem? ............................................135 You create an ASP.NET application that contains confidential information. You use form-based authentication to validate users. You need to prevent unauthenticated users from accessing the application. ..............................135 Which one of the following is not present in .NET Framework 1.1................136 Which one of the following is new in .NET Framework 2.0...........................136 How many generations are there in Garbage Collection..............................136

What is the core .NET Framework DLL.........................................................137 What are bubbled Events.............................................................................137 what are the common properties in every validation control?....................137 Order of methods fired during the page load?.............................................138 What type of code is found in a Code-Behind class?....................................138 What are core components of SqlServer 2005 ...........................................139 What property do you have to set to tell the grid which page to go to when using the Pager object?................................................................................ 139 What are the different types of assemblies available ?................................139 How many classes can a single .NET DLL contain?......................................140 What data types do the RangeValidator control support?............................140 Which of these string definitions will prevent escaping on backslashes in C#? ..................................................................................................................... 140 In a database we can able to create more than one primary key is it possible indirectly?..................................................................................................... 141 How to make a field as read only in a datagrid?..........................................141 Security is very important on any web site. By default, a .Net web site is configured with which of the following authentication types?......................141 can we have protected element as a namespace member?.......................142 Can we use access specifiers like public,private etc with namespace declaration?.................................................................................................. 142 What is the default join in SQL Server2000?................................................142 When ever you use DROP Table option in Sql server 2000 the indexes related to that table also deleted or not?.................................................................143 Why cant you specify the accessibility modifier for methods inside the interface?..................................................................................................... 143 Can multiple catch blocks be executed for a single try statement?.............143 What class is underneath the SortedList class?............................................144 How can you sort the elements of the array in descending order?..............144 Whats the difference between the System.Array.CopyTo() and System.Array.Clone()?.................................................................................. 144 You are a database developer for A Datum Corporation. You are creating a database that will store statistics for 15 different high school sports. 50 companies that publish sports information on their web sites will use this information. Each company's web site arranges and displays the statistics in a different format......................................................................................... 145

The CLR handles registration at run time. True?..........................................146 Which of the following incorrectly describe ASP.Net is?...............................146 Can As statement with Catch statement in error handling be omitted?.......146 Which namespace will be included for using the MsgBox( ) of VB 6.0?........147 can it possible to omit a parameter to a procedure that expects a ParamArray?................................................................................................. 147 Is it possible to use a function's name as local variable inside the procedure? ..................................................................................................................... 147 Passing an array using ByRef or ByVal makes a difference if u use a ReDim statement inside the called procedure. Which array size will be affected?. .147 ParamArray arguments are passed by in a function?...................................148 In global.asax file which event will occur first when you invoke an application? ..................................................................................................................... 148 What is difference between "tlbexp" and "Regasm" tools?..........................148 Is a string a value type or a reference type ?...............................................148 You use Visual Studio .NET to create a Windows-based application. The application enables users to update customer information that is stored in a database. Your application contains several text boxes. All TextBox controls are validated as soon as focus is transferred to another control. However, your validation code does not function as expected. To debug the application, you place the following line of code in the Enter event handler for the first text box: Trace.WriteLine(Enter); You repeat the proc...................................................................................... 149 1. You use Visual Studio .NET to create an application. Your application contains two classes, Region and City, which are defined in the following code segment. (Line numbers are included for reference only) 01 public class Region { 02 public virtual void CalculateTax() { 03 // Code to calculate tax goes here. 04 } 05 } 06 public class City:Region { 07 public override void CalculateTax() { 08 // Insert new code. 09 } 10 } You need to add code to the CalculateTax method of the City class to call t ..................................................................................................................... 150

What is the output of following C# code ?...................................................150 What is the output of following C# code ?...................................................152 What is the output of following C# code ?...................................................152 What is the output of following C# code ?...................................................153 Correction Number 2 ......*** How HR can "Help" to resolve any .NET developer is professional or pirated software user ? ........... Make years 2 and 1 year respectively instead of 3 in all three options.....................................154 **** Correction : .NET Garbedge Collector (GC) mark object as ? Make State , ........... not sate every place....................................................154 what is managed and unmanaged code?.....................................................154 Work Order of Garbedge Collector (GC) in .NET ?........................................155 The C# keyword int maps to which .NET type?..........................................155 Is it possible to restrict the scope of a field/method of a class to the classes in the same namespace?.................................................................................155 How do you implement thread synchronization (Object.Wait, Notify,and CriticalSection) in C#? - ............................................................................... 155 Is it possible to have different access modifiers on the get/set methods of a property?...................................................................................................... 156 How do you specify a custom attribute for the entire assembly (rather than for a class)? ................................................................................................. 156 How do I simulate optional parameters to COM calls?.................................157 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?..............................................157 What are the default user directory permissions when a Web site is created in IIS? ............................................................................................................. 157 An application using cookie authentication was working fine on another server. When moved to a new server, cookie authentication is not working correctly. Which one of the following is the likely explanation of the above problem? ..................................................................................................................... 158 How to create class for holding data?..........................................................158 Event handling in .NET is handled by which feature.....................................159 What is the value for i? int i = 0; while(i++ <10)

; Console.WriteLine("i = " + i);......................................................................159

.NET Framework

What is CTS
The common type system is a rich type system, built into the common language runtime, that supports the types and operations found in most programming languages. The common type system supports the complete implementation of a wide range of programming languages.

What is a CLS
The Common Language Specification is a set of constructs and constraints that serves as a guide for library writers and compiler writers. It allows libraries to be fully usable from any language supporting the CLS, and for those languages to integrate with each other. The Common Language Specification is a subset of the common type system. The Common Language Specification is also important to application developers who are writing code that will be used by other developers. When developers design publicly accessible APIs following the rules of the CLS, those APIs are easily used from all other programming languages that target the common language runtime.

What is a Assembly
An assembly is the primary building block of a .NET Framework application. It is a collection of functionality that is built, versioned, and deployed as a single implementation unit (as one or more files). All managed types and resources are marked either as accessible only within their implementation unit, or as accessible by code outside that unit. Assemblies are self-describing by means of their manifest, which is an integral part of every assembly. The manifest:

Establishes the assembly identity (in the form of a text name), version, culture, and digital signature (if the assembly is to be shared across applications). Defines what files (by name and file hash) make up the assembly implementation. Specifies the types and resources that make up the assembly, including which are exported from the assembly. Itemizes the compile-time dependencies on other assemblies. Specifies the set of permissions required for the assembly to run properly.

This information is used at run time to resolve references, enforce version binding policy, and validate the integrity of loaded assemblies. The runtime can determine and locate the assembly

for any running object, since every type is loaded in the context of an assembly. Assemblies are also the unit at which code access security permissions are applied. The identity evidence for each assembly is considered separately when determining what permissions to grant the code it contains. The self-describing nature of assemblies also helps makes zero-impact install and XCOPY deployment feasible.

What is the difference between a namespace and an assembly name?


A namespace is a logical naming scheme for types in which a simple type name, such as MyType, is preceded with a dot-separated hierarchical name. Such a naming scheme is completely under the control of the developer. For example, types MyCompany.FileAccess.A and MyCompany.FileAccess.B might be logically expected to have functionality related to file access. The .NET Framework uses a hierarchical naming scheme for grouping types into logical categories of related functionality, such as the Microsoft ASP.NET application framework, or remoting functionality. Design tools can make use of namespaces to make it easier for developers to browse and reference types in their code. The concept of a namespace is not related to that of an assembly. A single assembly may contain types whose hierarchical names have different namespace roots, and a logical namespace root may span multiple assemblies. In the .NET Framework, a namespace is a logical design-time naming convenience, whereas an assembly establishes the name scope for types at run time.

What is Manifest What is GAC What is concept of strong names How to add and remove a assembly from GAC What is an application domain
An application domain (often AppDomain) is a virtual process that serves to isolate an application. All objects created within the same application scope (in other words, anywhere along the sequence of object activations beginning with the application entry point) are created within the same application domain. Multiple application domains can exist in a single operating system process, making them a lightweight means of application isolation.

An OS process provides isolation by having a distinct memory address space. While this is effective, it is also expensive, and does not scale to the numbers required for large web servers. The Common Language Runtime, on the other hand, enforces application isolation by managing the memory use of code running within the application domain. This ensures that it does not access memory outside the boundaries of the domain. It is important to note that only type-safe code can be managed in this way (the runtime cannot guarantee isolation when unsafe code is loaded in an application domain).

Structures:
1. Structures are sealed and cannot be inherited 2. Structures cannot inherit classes and other structures 3. Structure implicitly inherits from System.ValueType 4. The default constructor of a structure cannot be replaced by a custom constructor 5. Structures do not have destructors

Classes:

Class Modifier Table


Modifier Abstract Sealed static Unsafe Description Class is abstract; future instances of the class cannot be created. Class cannot be inherited and refined in a derived class. Class contains only static members. Class can contain unsafe constructs, such as a pointer; requires the unsafe compiler option.

Member Accessibility
Accessibility internal private Description Visible in containing assembly Visible inside current class

internal protected Visible in containing assembly or descendants of the current class

Accessibility protected public

Description Visible inside current class and any descendants Visible in containing assembly and assemblies referencing that assembly

Member Modifiers
Modifier abstract Extern New Override Description A member function has no implementation and is described through inheritance. Implemented in a foreign dynamic-link library (DLL). Hides a similar member or members in the base class. Indicates that a function in a derived class overrides a virtual method in the base class. The member function cannot be further refined through inheritance. Member belongs to a class and not an instance. Virtual functions are overridable in a derived class. Volatile fields are modifiable by the environment, a separate thread, or hardware.

Readonly Read-only fields are initialized at declaration or in a constructor. Sealed Static Virtual Volatile

Instance Constructors: Static Constructors:


The static constructor is invoked before the class is accessed in any manner. There are limitations to static constructors, as follows: Static constructors cannot be called explicitly. Accessibility defaults to static, which cannot be set explicitly. Static constructors are parameter less. Static constructors cannot be overloaded. Static constructors are not inheritable.

The return type cannot set explicitly. Constructors always return void. Static constructors are called before a static member or an instance of the classes is accessed

Implement a Singleton using Static Constructor:


namespace Donis { public class Chessboard { private Chessboard() { } static Chessboard() { board=new Chessboard(); board.start=DateTime.Now.ToShortTimeString(); } public static Chessboard board=null; public string player1; public string player2; public string start; } public class Game{ public static void Main(){ Chessboard game=Chessboard.board; game.player1="Sally"; game.player2="Bob"; Console.WriteLine("{0} played {1} at {2}", game.player1, game.player2, game.start); } } }

Nullable Types:
Assigning a null to an object indicates that it is unused Nullable types are a consistent solution for determining whether a value object is empty. Declare a nullable type by adding the ? type modifier in a value type declaration. Here is an example: double? variable1=null;

Identity versus Equivalence


Equivalence is the value or state of an instance. Related instances that have the same value are equivalent. Identity is the location of an object.

System.Object
All managed types inherit from System.Object, either directly or indirectly Value types inherit from System.ValueType, which then inherits System.Object. System.ValueType overrides System.Object members to implement the semantics of a value type.

Object.Equals Method
For reference types, the Object.Equals method compares identity. References are equal when pointing to the same object. References that point to different objects but have the same state are not equal

Object.ReferenceEquals Method
The ReferenceEquals method compares identity. If the objects are the same, ReferenceEquals returns true. Otherwise, false is returned. ReferenceEquals is not virtual and cannot be overridden in the derived class

Collections
.NET FCL offers a variety of other collections with different semantics Collection Types Class Name Description ArrayList BitArray Hashtable Queue SortedList Stack Dynamic array Bit array Lookup table of keys and values First-in/first-out (FIFO) collection of elements Sorted list of elements Last-in/first-out (LIFO) collection of elements

Generics:

A simple solution is generic implementation, which is single implementation for all types. Inheritance polymorphism, which is polymorphism using inheritance and virtual functions, is an alternate solution to type specialty. Using it solves some of the problems, such as code reuse. This is a potential solution to generic abstraction but not a generic data algorithm. Abstracting the stack algorithm based on inheritance encourages bad design. Is a stack a kind of integer? Is an integer a kind of stack? Neither statement is true. For a stack solution, inheritance polymorphism is a contrived solution at best.

Generic types and methods are not suitable in all circumstances.


The entry point method cannot be a member of an generic type. Unmanaged types cannot be generic. Constructors cannot be generic. Operator member functions cannot be generic methods. Properties cannot be generic. Indexers cannot be generic. Attributes cannot be generic.

Generic Types
Generics are types with parameters, and parameters are placeholders for future types. Generic types include classes, structures, and interfaces. The essence of the type remains. The persona of a class, even a generic class, remains a classit is simply a class with type parameters.

Delegates and Events


Function pointers are indirect references to functions and support calling functions through variables. With function pointers, you can pass a function as a parameter to a function or as a return type. Function pointers are an important ingredient of many programming languages, including C, C++, and Microsoft Visual Basic. Function pointers can make applications more flexible, extensible, and scalable. Function pointers have been the source of many application bugs, however, because function pointers point to raw bytes of memory. Function pointers are not type-safe, and calling an incompatible

method through a function pointer is an infrequent error. .NET has delegates that are essentially type-safe function pointers. Unlike function pointers in other languages, particularly C and C++, delegates are type-safe, object-oriented, and secure. This reduces common problems associated with using function pointers.
A delegate is an abstraction of one or more function pointers. Delegates are derived from System.MulticastDelegate, which is a reference type. System.MulticastDelegate is derived from System.Delegate. Delegates are useful as general function pointers, callbacks, events, and threads. As a general function pointer, a delegate can be a method parameter, function return, class member, or local variable. Callbacks are valuable in many scenarios, including promoting peer-to-peer relationships, in which objects swap function pointers to send bilateral messages. Events support a publisher/subscriber model. The publisher notifies subscribers of events, whereas the subscriber registers functions to be called when the event occurs. Finally, a delegate is a path of execution for a thread, which is an asynchronous function call

Covariance and contravariance


Covariance and contravariance provide a degree of flexibility when matching method signatures with delegate types. Covariance permits a method to have a more derived return type than what is defined in the delegate. Contravariance permits a method with parameter types that are less derived than in the delegate type.

Inheritance versus composition: Which one should you choose?


Dynamic binding, polymorphism, and change o When you establish an inheritance relationship between two classes, you get to take advantage of dynamic binding and polymorphism One of the prime benefits of dynamic binding and polymorphism is that they can help make code easier to change

Changing the superclass interface o In an inheritance relationship, superclasses are often said to be "fragile," because one little change to a superclass can ripple out and require changes in many other places in the application's code.

Don't use inheritance just to get code reuse If all you really want is to reuse code and there is no is-a relationship in sight, use composition. Don't use inheritance just to get at polymorphism If all you really want is polymorphism, but there is no natural is-a relationship, use composition with interfaces. I'll be talking about this subject next month.

Delayed Signing
An organization can have a closely guarded key pair that developers do not have access to on a daily basis. The public key is often available, but access to the private key is restricted to only a few individuals. When developing assemblies with strong names, each assembly that references the strong-named target assembly contains the token of the public key used to give the target assembly a strong name. This requires that the public key be available during the development process. You can use delayed or partial signing at build time to reserve space in the portable executable (PE) file for the strong name signature, but defer the actual signing until some later stage (typically just before shipping the assembly).

Casting Operators Implementing a C# Collection


Implement the ICollection Interface in a Custom Class Implement an Enumerator Object for the GetEnumerator Method Using For Each to Iterate Through the Custom Collection

Implementing Finalize and Dispose to Clean Up Unmanaged Resources


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.

Finalize
The following rules outline the usage guidelines for the Finalize method:
Only implement Finalize on objects that require finalization. There are performance costs associated with Finalize methods. If you require a Finalize method, you should consider implementing IDisposable to allow users of your class to avoid the cost of invoking the Finalize method. Do not make the Finalize method more visible. It should be protected, not public. An object's Finalize method should free any external resources that the object owns. Moreover, a Finalize method should release only resources that are held onto by the object. The Finalize method should not reference any other objects. Do not directly call a Finalize method on an object other than the object's base class. This is not a valid operation in the C# programming language. Call the base.Finalize method from an object's Finalize method. Note The base class's Finalize method is called automatically with the C# and the Managed Extensions for C++ destructor syntax.

Dispose
The following rules outline the usage guidelines for the Dispose method:
Implement the dispose design pattern on a type that encapsulates resources that explicitly need to be freed. Users can free external resources by calling the public Dispose method. Implement the dispose design pattern on a base type that commonly has derived types that hold on to resources, even if the base type does not. If the base type has a close method, often this indicates the need to implementDispose. In such cases, do not implement a Finalize method on the base type. Finalize should be implemented in any derived types that introduce resources that require cleanup. Free any disposable resources a type owns in its Dispose method. After Dispose has been called on an instance, prevent the Finalize method from running by calling the GC.SuppressFinalize Method. The exception to this rule is the rare situation in which work must be done in Finalize that is not covered by Dispose. Call the base class's Dispose method if it implements IDisposable. Do not assume that Dispose will be called. Unmanaged resources owned by a type should also be released in a Finalize method in the event that Dispose is not called. Throw an ObjectDisposedException from instance methods on this type(other than Dispose) when resources are already disposed. This rule does not apply to the Dispose method because it should be callable multiple times without throwing an exception. Propagate the calls to Dispose through the hierarchy of base types. The Dispose method should free all resources held by this object and any object owned by this object. For example, you can create an object like a TextReader that holds onto a Stream and an Encoding, both of which are created by the TextReader without the user's knowledge. Furthermore, both the Stream and the Encoding can acquire external resources. When you call the Dispose method on the TextReader, it should in turn call Dispose on the Stream and the Encoding, causing them to release their external resources. You should consider not allowing an object to be usable after its Dispose method has been called. Recreating an object that has already been disposed is a difficult pattern to implement.

Allow a Dispose method to be called more than once without throwing an exception. The method should do nothing after the first call.

What size is a .NET object?


Each instance of a reference type has two fields maintained by the runtime - a method table pointer and a sync block. These are 4 bytes each on a 32-bit system, making a total of 8 bytes per object overhead. Obviously the instance data for the type must be added to this to get the overall size of the object. So, for example, instances of the following class are 12 bytes each:

class MyInt { ... private int x; }


However, note that with the current implementation of the CLR there seems to be a minimum object size of 12 bytes, even for classes with no data (e.g. System.Object). Values types have no equivalent overhead.

Can you prevent your class from being inherited by another class Passing a Variable Number of Parameters to a Method
public void ObjectParams(string Message, params object[] p) { Console.WriteLine(Message); for (int i = 0; i < p.Length; i++) { Console.WriteLine(p[i]); } }

Dump Method Names using Reflection:


LoadAssembly Assembly.ReflectionOnlyLoad MethodInfo [] GetMethods();

MethodInfo[] GetMethods(BindingFlags binding) ParameterInfo[] using MethodInfo .GetParameters())

Dynamic Invocation using Relection:


MethodInfo.Invoke

Indexers
Indexers allow instances of a class or struct to be indexed just like arrays. Indexers resemble properties except that their accessors take parameters.

Reflection:
An assembly is a piata stuffed with goodies such as type information, MSIL code, and custom attributes. You use reflection to break open the assembly piata to examine the contents. Reflection adds important features to .NET, such as metadata inspection, run-time creation of types, late binding, MSIL extraction, self-generating code, and so much more. These features are crucial to solving complex real-world problems that developers face every day. The central component of reflection is the Type object. Its interface can be used to interrogate a reference or value type. This includes browsing methods, fields, parameters, and custom attributes. General information pertaining to the type is also available via reflection, including identifying the hosting assembly. Beyond browsing, Type objects support more intrusive operations. You can create instances of classes at run time and perform late binding of methods.

Obtaining a Type Object


The Object.GetType method, the typeof operator, and various methods of the Assembly object return a Type object. GetType is a member of the Object class, which is the ubiquitous base class. Therefore, GetType is inherited by .NET types and available to all managed instances. Each instance can call GetType to return the related Type object. The typeof operator extracts a Type object directly from a reference or value type. Assembly objects have several members that return one or more Type objects. For example, the Assembly.GetTypes method enumerates and returns the Types of the target assembly.

The typeof operator returns a Type object from a type. The typeof operator is evaluated at compile time, whereas the GetType method is invoked at run time. For this reason, the typeof operator is quicker but less flexible than the GetType method:

Loading Assemblies
Assembly.Load uses the assembly loader to locate and bind to the correct assembly. Assembly.LoadFrom consults the assembly resolver to locate an assembly, which uses a combination of the strong name identifier and probing to bind and then load an assembly. Both Assembly.Load and Assembly.LoadFrom return a reference to an assembly. That assembly can be reflected, code loaded, and then executed. Assembly.ReflectionOnlyLoad and Assembly.ReflectionOnlyLoadFrom load an assembly only for reflection, so the code cannot be executed later. Although you could reflect a type and iterate all the methods, you could not invoke a method of that type. Type.ReflectionOnlyGetType combines the functionality of Assembly.ReflectionOnlyLoad and the typeof operator. The named assembly is loaded for inspection only, and a Type object is returned to the specified type. Because the assembly is opened only for browsing, you cannot create an instance of the type or invoke a method on the type. ReflectionOnlyGetType is a static method of the Type class and loads a Type for inspection only. The method returns a Type object:

Browsing Type Information


Inspecting a type begins with the Type object. Type.GetMembers returns the ultimate collection: the collection of all members. All members, whether the member is a method, field, event, or property, are included in the collection.

Checked and UnChecked Operators


checked { // Start of checked block Byte b = 100; b = (Byte) (b + 200); // This expression is checked for overflow. }

Difference between ReadOnly field and constant field Advantage of anonymous delegate

Can a structure have default constructor What is a satellite assembly What is an appdomain? What is boxing and Unboxing. What happens when a value type is added to an arraylist What is serialization Difference between
try { } catch { } And Using( ) { }

Write a function in C# that will take one input parameter and return true if given input type is int or long else false? What is static class? And how it is different from normal class? What is the difference between ref and out keywords in C#?

What is delegate? What is the difference between delegate and event? What is polymorphism? What is the importance of new and override operators (key words) in terms of Polymorphism? What is the difference between Array and Dictionary? When to use what? What is the purpose of GAC? What are the prerequisites for putting a dll in GAC? What is the difference between "overload" and "override" in C#?
Memory Management: Creational Patterns

Abstract Factory - Creates an instance of several families of classes Builder - Separates object construction from its representation Factory Method - Creates an instance of several derived classes Prototype - A fully initialized instance to be copied or cloned

Singleton - A class of which only a single instance can exist


Structural Patterns

Adapter - Match interfaces of different classes Bridge - Separates an objects interface from its implementation Composite - A tree structure of simple and composite objects Decorator - Add responsibilities to objects dynamically Faade - A single class that represents an entire subsystem Flyweight - A fine-grained instance used for efficient sharing Proxy - An object representing another object
Behavioral Patterns

Chain of Responsibility - A way of passing a request between a chain of objects Command - Encapsulate a command request as an object

Interpreter - A way to include language elements in a program Iterator - Sequentially access the elements of a collection Mediator - Defines simplified communication between classes Memento - Capture and restore an object's internal state Observer - A way of notifying change to a number of classes State - Alter an object's behavior when its state changes Strategy - Encapsulates an algorithm inside a class Template Method - Defer the exact steps of an algorithm to a subclass Visitor - Defines a new operation to a class without change

Question: What is purpose of Assembly Linker or define SDK Tool in .NET Framework? Answer: In .NET whole the working should be with the helps of DLLs.So all of Visual Studio .Net compilers gernate assemblies or u can say dll.If we want to create an assembly with manifest of a module.We can also put this assembly in seprate file.This AL tol gernate a file with an assembly manifest from modules or resources fles.The syntax of using Al.exe is al [sources] [options]

This tool helps in creating multi-file assembly outside Visual Studio .Net .This multi file can contain modules that are written in diffrenet langauage in one application. Question: What do u mean by Satellite Assemblies ? Answer: The assemblies which contains only culture information are known as satellite assemblies.This assembly is used to get language specific resources for an application . Question: Whats the difference between private and shared assembly? Answer: Privateassembly 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. Question: What do you know about .NET assemblies? Answer: 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. Question: Whats a strong name ? Answer: A strong name includes the name of the assembly, version number, culture identity, and a public key token. Question: Whats an assembly ? Answer: Assemblies are the building blocks of .NET Framework applications; they form the fundamental unit of deployment, version control, reuse, activation scoping, and security permissions. An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. An assembly provides the common language runtime with the information it needs to be aware of type implementations. To the runtime, a type does not exist outside the context of an assembly. Question: How can you debug failed assembly binds ? Answer: Use the Assembly Binding Log Viewer (fuslogvw.exe) to find out the paths searched. Question: Where are shared assemblies stored ? Answer: Global assembly cache. Question: How can you tell the application to look for assemblies at the locations other than its own install ? Answer: Use the directive in the XML .config file for a given application. <probing privatePath="c:\mylibs; bin\debug /> should do the trick. Or you can add additional search paths in the Properties box of the deployed application. Question: Wheres global assembly cache located on the system ? Answer: Usually C:\winnt\assembly or C:\windows\assembly.

Question: How do you specify a custom attribute for the entire assembly (rather than for a class) ? Answer: 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. Question: What is delay signing ? Answer: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.

Question: What Is OOPS ? Answer: OOPs is an Object Oriented Programming language,which is the extension of Procedure Oriented Programming language.OOPS reduce the code of the program because of the extensive feature of Polymorphism. OOPS have many properties such as Data-Hiding,Inheritence,Data Absraction,Data Encapsulation and many moreEverything in the world is an object. The type of the object may vary. In OOPS, we get the power to create objects of our own, as & when required. Question: what is Class ? Answer:A group of objects that share a common definition and that therefore share common properties, operations, and behavior. A user-defined type that is defined with the class-key 'class,' 'struct,' or 'union.' Objects of a class type consist of zero or more members and base class objects.Classes can be defined hierarchically, allowing one class to be an expansion of another, and classes can restrict access to their members. Question: What is Constructor? Answer:When we create instance of class a special method of that class, called that is constructor. Similarly, when the class is destroyed, the destructor method is called. These are general terms and usually not the actual member names in most object-oriented languages. It is initialized using the keyword New, and is destroyed using the keyword Finalize. Question: What is Abstract Class ? Answer:Classes that cannot be instantiated. We cannot create an object from such a class for use in our program. We can use an abstract class as a base class, creating new classes that will inherit from it. Creating an abstract class with a certain minimum required level

of functionality gives us a defined starting point from which we can derive non-abstract classes. An abstract class may contain abstract methods & non-abstract methods. When a class is derived from an abstract class, the derived class must implement all the abstract methods declared in the base class. We may use accessibility modifiers in an abstract class.An abstract class can inherit from a non-abstract class. In C++, this concept is known as pure virtual method. Question: What is ValueType? Answer:Value Types - Value types are primitive types. Like Int32 maps to System.Int32, double maps to System.double.All value types are stored on stack and all the value types are derived from System.ValueType. All structures and enumerated types that are derived from System.ValueType are created on stack, hence known as ValueType.In value type we create a copy of object and uses there value its not the original one. Question: What is diff. between abstract class and an interface? Answer: An abstract class and Interface both have method only but not have body of method.The difference between Abstract class and An Interface is that if u call Ablstract class then u have to call all method of that particular Abstract class but if u call an Interface then it is not necessary that u call all method of that particular interface.Method OverLoading:-Return type, Parameter type, parameter and body of method number may be different.Method Overriding:- Return type, Parameter type, Parameter Number all must be same . Only body of method can change. Question:Type of garbage collector? Answer:There are two types of Garbage Collector managed garbage collector see we will declaring variable ,object in our programes once this kind of variable,object goes out of the scope ,they are put into the heap and they are checked for the further existence.once its beeing no longer used garbage collector wil deallcate mem for that variable and objects. Umanaged garbage collector this was done mannually and u will be happen to open a connection with database,will be open the file etc. while this kind of the thing goes out of the scope we have to explicitly call the garage colector by calling the closecommand of the datbase once the connection is closed it puts this memmory ino the heep and process follws the same Question:Option statements that are supported in VB.NET? Option Explicit:- By default, Option Explicit is on for VB.NET projects. It's a good programming practice to set Option Explicit on because it helps developers avoid implicitly declaring variables, and thus write

better code.This forces developers to explicitly declare variables utilizing the Dim keyword and specifying the datatype for the variable. Option Compare:-By default,the Option Compare is Binary;however,you can set Option Compare to Text instead. Option Strict:- Option Strict Off is the default mode for the code in VB.NET; however, it's preferable to write code with Option Strict on. Option Strict On prevents implicit type conversions by the compiler. It's also a safer way to develop code, which is why most developers prefer it.

Taken from Developing Windows-Based Applications with Microsoft Visual Basic .NET and Microsoft Visual C# .NET. book Questions and Answers Chapter 1: Introduction to the .NET Framework 1. Briefly describe the major components of the .NET Framework and describe what each component does. The .NET Framework consists of two primary parts: the common language runtime, which manages application execution, enforces type safety, and manages memory reclamation, and the .NET base class library, which consists of thousands of predeveloped classes that can be used to build applications. 2. Briefly explain what is meant by a reference type and a value type. A value type holds all of the data represented by the variable within the variable itself. A reference type contains a reference to a memory address that holds the data instead of the actual data itself. 3. How do you enable your application to use .NET base class library members without referencing their fully qualified names? Use the Imports keyword (Visual Basic .NET) or the using keyword (Visual C#) to make a .NET Framework namespace visible to your application. 4. Briefly describe how garbage collection works.

The garbage collector is a thread that runs in the background of managed .NET applications. It constantly traces the reference tree and attempts to find objects that are no longer referenced. When a nonreferenced object is found, its memory is reclaimed for later use. 5. Briefly describe what members are, and list the four types of members. Members are the parts of a class or a structure that hold data or implement functionality. The primary member types are fields, properties, methods, and events. 6. Explain what constructors and destructors are and describe what they are used for. The constructor is the method that initializes a class or structure and is run when a type is first instantiated. It is used to set default values and perform other tasks required by the class. A destructor is the method that is run as the object is being reclaimed by garbage collection. It contains any code that is required for cleanup of the object. 7. Briefly explain the difference between Public (public), Friend (internal), and Private (private) access levels as they apply to user-defined types and members. In user-defined types, Public (public) classes can be instantiated by any element of the application. Friend (internal) classes can be instantiated only by members of the same assembly, and Private (private) classes can be instantiated only by themselves or types they are nested in. Likewise, a Public (public) member can be accessed by any client in the application, a Friend (internal) member can be accessed only from members of the same assembly, and Private (private) members can be accessed only from within the type. 8. Do you need to instantiate a class before accessing a Shared (static) member? Why or why not? Because a Shared (static) member belongs to the type rather than to any instance of the type, you can access the member without first creating an instance of the type. 9. Briefly describe how a class is similar to a structure. How are they different? Both classes and structures can have members such as methods, properties, and fields, both use a constructor for initialization, and both inherit from System.Object. Both classes and structures can be used to model realworld objects.

Classes are reference types, and the memory that holds class instances is allocated on the heap. Structures are value types, and the memory that holds structure instances is allocated on the stack. Chapter 2: Creating the User Interface 1. You are creating an application for a major bank. The application should integrate seamlessly with Microsoft Office XP, be easy to learn, and instill a sense of corporate pride in the users. Name two ways you might approach these goals in the user interface. Design the user interface to mimic the look and feel of Microsoft Office XP, which will allow users of Office XP to immediately feel comfortable with the new application. Integration of the corporate logo and other visual elements associated with the company will aid in identification of the program with the company. 2. You are writing an application that needs to display a common set of controls on several different forms. What is the fastest way to approach this problem? Create a single form that incorporates the common controls, and use visual inheritance to create derived forms. 3. If you wanted to prompt a user for input every time a form received the focus, what would be the best strategy for implementing this functionality? Write an event handler for the Activated event that implements the relevant functionality. 4. Describe two ways to set the tab order of controls on your form. You can set the tab order in Visual Studio by choosing Tab Index from the View menu and clicking each control in the order you desire. Alternatively, you can set the TabIndex property either in code or in the Properties window. 5. What is an extender provider, and what does one do? Extender providers are components that provide additional properties to controls on a form. Examples include the ErrorProvider, HelpProvider, and ToolTip components. They can be used to provide additional information about particular controls to the user in the user interface. 6. Explain when you might implement a shortcut menu instead of a main menu. If every possible option is exposed on a main menu, the menu can become busy and hard to use. Shortcut menus allow less frequently used options to be exposed only in situations where they are likely to be used.

7. Describe what is meant by field-level validation and form-level validation. Field-level validation is the process of validating each individual field as it is entered into a form. Form-level validation describes the process of validating all of the data on a form before submitting the form. 8. Describe how to retrieve the ASCII key code from a keystroke. How would you retrieve key combinations for non-ASCII keys? Keystrokes can be intercepted by handling the KeyPress and KeyDown events. Both of these events relay information to their handling methods in the form of their EventArgs. The KeyPressEventArgs, relayed by the Key-Press event, exposes the ASCII value of the key pressed in the KeyPressEventArgs. KeyChar property. The KeyEventArgs, relayed by the KeyDown event, exposes properties that indicate whether non-ASCII keys such as ALT, CTRL, or Shift have been pressed. To retrieve the ASCII key code from a keystroke, you would handle the KeyPress event and get that information from the KeyPressEventArgs.KeyChar property. To retrieve non-ASCII information, you would handle the KeyDown event and use the properties exposed by the KeyEventArgs instance. 9. Describe in general terms how to add a control to a form at run time. You must first declare and instantiate a new instance of the control. Then, you must add the control to the forms Controls collection. Once the control has been added to the Controls collection, you must manually set properties that govern the controls position and appearance. Chapter 3: Types and Members 1. Explain when a type conversion will undergo an implicit cast and when you must perform an explicit cast. What are the dangers associated with explicit casts? Types can be implicitly converted when the conversion can always take place without any potential loss of data. When a potential loss of data is possible, an explicit cast is required. If an explicit cast is improperly performed, a loss of data precision can result, or an exception can be thrown. 2. Explain why you might use enums and constants instead of their associated literal values. Enums and constants make code easier to read and maintain by substituting human-legible tokens for frequently used constant values. 3. Briefly summarize the similarities and differences between arrays and collections.

Arrays and collections allow you to manage groups of objects. You can access a particular object by index in both arrays and collections, and you can use For EachNext (foreach) syntax to iterate through the members of arrays and most collections. Arrays are fixed in length, and members must be initialized before use. Members of collections must be declared and initialized outside of the collection, and then added to the collection. Collections provided in the System.Collections namespace can grow or shrink dynamically, and items can be added or removed at run time. 4. Explain how properties differ from fields. Why would you expose public data through properties instead of fields? Properties allow validation code to execute when values are accessed or changed. This allows you to impose some measure of control over when and how values are read or changed. Fields cannot perform validation when being read or set. 5. Explain what a delegate is and how one works. A delegate acts like a strongly typed function pointer. Delegates can invoke the methods that they reference without making explicit calls to those methods. 6. Briefly explain how to convert a string representation of a number to a numeric type, such as an Integer or a Double. All numeric data types have a Parse method that accepts a string parameter and returns the value represented by that string cast to the appropriate data type. You can use the Parse method of each data type to convert strings to that type. 7. What are the two kinds of multidimensional arrays? Briefly describe each. Multidimensional arrays can be either rectangular arrays or jagged arrays. A rectangular array can be thought of as a table, where each row has the same number of columns. Rectangular arrays with more than two dimensions continue this concept, where each member of each dimension has the same number of members of each other dimension. Jagged arrays can be thought of as an array of arrays. A two-dimensional jagged array is like a table where each row might have a different number of columns. Chapter 4: Object-Oriented Programming and Polymorphism 1. Briefly explain encapsulation and why it is important in object-oriented programming. Encapsulation is the principle that all of the data and functionality required by an object be contained by that object. This allows objects to exist as independent,

interchangeable units of functionality without maintaining dependencies on other units of code. 2. What is method overloading, and when is it useful? Method overloading allows you to create several methods with the same name but different signatures. Overloading is useful when you want to provide the same or similar functionality to different sets of parameters. 3. You need to create several unrelated classes that each exposes a common set of methods. Briefly outline a strategy that will allow these classes to polymorphically expose that functionality to other classes. Factor the common set of methods into an interface, and then implement that interface in each class. Each class can then be implicitly cast to that interface and can polymorphically interact with other classes. 4. You need to create several classes that provide a core set of functionality but each must be able to interact with a different set of objects. Outline a strategy for developing these classes with the least development time. Create a single class that implements all of the common functionality required by these classes. Then, use inheritance to create derived classes that are specific for each individual case. 5. Describe an abstract class and explain when one might be useful. An abstract class is a class that cannot be instantiated but must be inherited. It can contain both implemented methods and abstract methods, which must be implemented in an inheriting class. Thus, it can define common functionality for some methods, a common interface for other methods, and leave more detailed implementation up to the inheriting class. Chapter 5: Testing and Debugging Your Application 1. Describe Break mode and some of the available methods for navigating in Break mode. Break mode allows you to observe program execution on a line-by-line basis. You can navigate program execution in Break mode by using Step Into, Step Over, Step Out, Run To Cursor, and Set Next Statement. 2. When would you use the Watch window? You would use the Watch window to observe the values of application variables while in Break mode.

3. You are deploying a beta version of a large application and want to collect performance data in text files while the application is in use. Briefly describe a strategy for enabling this scenario. Place Trace statements that report the data of interest throughout the application. Create a TextWriterTraceListener and add it to the Listeners collection. Create Trace switches that control when Trace statements are executed. Configure the TextWriterTraceListener to write output to a text file. Then, compile and deploy the application with Trace defined, and enable the Trace switches in the application .config file. 4. When testing a method, should you test data that is known to be outside of the bounds of normal operation? Why or why not? Yes. In addition to testing normal data operation, you must test known bad input to ensure that your application can recover from input errors without a catastrophic application failure. 5. Briefly explain what each segment of a TryCatchFinally (try...catch...finally) block does. The Try (try) block encloses code that is to be executed. If an exception is thrown, it can be caught in an appropriate Catch (catch) block where code that will allow the application to handle the execution will be executed. The Finally (finally) block contains any code that must be executed whether or not the exception is handled. Chapter 6: Data Access with ADO.NET 1. What are the major components of a Data Provider, and what function does each fulfill? An ADO.NET Data Provider is a suite of components designed to facilitate data access. Every Data Provider minimally includes a Connection object that provides the actual connection to the data source, a Command object that represents a direct command to the data source, a DataReader object that provides connected, forward-only, read-only access to a database, and a DataAdapter that facilitates disconnected data access. 2. Briefly contrast connected and disconnected data access in ADO.NET. In ADO.NET, connected data access is available through the DataReader, which is a lightweight class designed to provide very fast and efficient data access. It is severely limited, however, in that it can only provide forward-only data access, it does not allow editing, and it requires the exclusive use of a Connection object. In contrast, disconnected data access is facilitated by a DataAdapter, which manages

the commands required for selecting and updating data. The DataAdapter executes a SELECT command against a database, opening a data connection just long enough to retrieve the data, and loads the data into a DataSet, which is an inmemory copy of the data. When the data is ready to be updated, the Data Provider manages the updates in the same way, generating the appropriate commands to update the database and keeping the connection open just long enough to execute those commands. 3. What are the three possible settings for the CommandType property of a SqlCommand object or an OleDbCommand object, and what does each mean? A Command object can have a CommandType property setting of Text, StoredProcedure, or TableDirect. When set to Text, the command executes the SQL string that is stored in the Command objects CommandText property. When set to StoredProcedure, the command accesses a procedure stored on the database and returns the results. A CommandText setting of TableDirect indicates that the command should return the entire contents of the table indicated by the CommandText property. 4. How could you execute DDL commands, such as ALTER or CREATE TABLE, against a database with ADO.NET? You must use a Command object to execute DDL commands. You can set the CommandType property to Text and enter the appropriate DDL command in the CommandText property. Then call Command.ExecuteNonQuery to execute the command. 5. Briefly discuss the advantages and disadvantages of using typed DataSet objects. Typed DataSet objects allow you to work with data that is represented as members of the .NET common type system. This allows your applications to be aware of the types of data returned in a DataSet and serves to eliminate errors resulting from invalid casts, as any type mismatches are caught at compile time. Untyped DataSet objects, however, are useful if you do not know the structure of your data, and can be used with any data source. 6. How can you manage data currency on a form with several bound controls? Every data source on a form has an associated CurrencyManager object that keeps that of the current record with respect to bound controls. For convenience, all of the CurrencyManager objects represented on a form are exposed through the forms BindingContext property. The Position of the CurrencyManager can be changed, allowing navigation through the records. 7. Describe how to use a DataView to filter or sort data.

You can apply sort criteria to a DataView by setting the Sort property to the name of a column or columns to be sorted by. The data represented in a DataView object can be filtered by setting the RowFilter property to a valid filter expression. 8. Briefly describe an XmlDataDocument and how it relates to a DataSet. An XmlDataDocument is an in-memory representation of data in a hierarchical XML format. Each XmlDataDocument is synchronized with a DataSet. Whenever changes are made to one object, the other is instantly updated. Thus, you can use the XmlDataDocument to perform XML manipulations on a DataSet. 9. What are the four major parts of a SQL SELECT statement? Briefly describe each one. The four major parts of a SELECT statement are SELECT, FROM, WHERE, and ORDER BY. SELECT specifies the fields to be retrieved. FROM specifies the table from which the records are to be retrieved. WHERE allows you to specify filter criteria for the records to be retrieved, and ORDER BY allows you to specify a sort order for the records. 10. In Visual Basic .NET or Visual C# programming, when would you use Structured Query Language (SQL)? How are they executed? ADO.NET handles most of the database communication for you behind-thescenes. You would only use SQL statements when generating ad-hoc queries for the database. You execute SQL statements by using a DataCommand object. Statements the return records, such as SELECT statements, are executed using the ExecuteQuery method. You can also return a single value with a SELECT statement by using the ExecuteScalar method. To execute non-value returning statements, such as DELETE, INSERT INTO, or UPDATE statements, use the ExecuteNonQuery method. 11. What is meant by a SQL injection attack? How can you prevent them from occurring in your application? SQL injection attacks occur when a malicious user attempts to execute SQL code by passing a SQL string to the application through user input. You can guard against SQL injection attacks by validating the format of all strings derived from user input that are used to form ad hoc SQL statements. 12. How can you read XML data into a dataset? How would you write data in a dataset to an XML file? How would you retrieve a string representation of the XML contained within a dataset? Describe each in general terms. To read data from an XML file into a dataset, you can use the ReadXML method of the dataset, specifying the stream or file that contains the XML data. To write

data to a file, you can use the WriteXML method of the dataset, again specifying either the file or the stream that represents the file. The GetXML method of the dataset can be used to retrieve a string representation of the XML data contained by a dataset. Chapter 7: Creating Controls Using the .NET Framework 1. Briefly describe the three types of user-developed controls and how they differ. The three types of user-developed controls are inherited controls, user controls, and custom controls. An inherited control derives from a standard Windows Forms control and inherits the look, feel, and functionality of that control. User controls allow you to combine standard Windows Forms controls and bind them together with common functionality. Custom controls inherit from Control and are the most development-intensive kind of control. Custom controls must implement all their own code for painting and inherit only generic control functionality. All specific functionality must be implemented by the developer. 2. Describe the roles of Graphics, Brush, Pen, and GraphicsPath objects in graphics rendering. The Graphics object represents a drawing surface and encapsulates methods that allow graphics to be rendered to that surface. A Brush is an object that is used to fill solid shapes, and a Pen is used to render lines. A GraphicsPath object represents a complex shape that can be rendered by a Graphics object. 3. Describe the general procedure for rendering text to a drawing surface. You must first obtain a reference to a Graphics object. Next, create an instance of a GraphicsPath object. Use the GraphicsPath.AddString method to add text to the GraphicsPath. Then, call the Graphics.DrawPath or Graphics.FillPath to render the text. 4. Describe the role of the LicenseProvider in control licensing. The LicenseProvider controls license validation and grants run-time licenses to validly licensed components. The LicenseManager.Validate method checks for an available license file and checks against the validation logic provided by the specific implementation of LicenseProvider. You specify which LicenseProvider to use by applying the LicenseProviderAttribute. 5. Describe how to create a form or control with a nonrectangular shape. Set the Region property of the form or control to a Region object that contains the irregular shape. You can create a Region object from a GraphicsPath object.

Chapter 8: Advanced .NET Framework Topics 1. Briefly describe how to use the PrintDocument component to print a document. Discuss maintaining correct line spacing and multipage documents. The PrintDocument class exposes the Print method, which raises the PrintPage event. Code to render printed items to the printer should be placed in the PrintPage event handler. The PrintPage event handler provides the objects required to render to the printer in an instance of the PagePrintEventArgs class. Content is rendered to the printer using the Graphics object provided by PagePrintEventArgs. You can calculate correct line spacing by dividing the height of the MarginBounds property by the height of the font you are rendering. If your document has multiple pages, you must set the PagePrintEventArgs.HasMorePages property to true, which causes the PrintPage event to fire again. Because the PrintPage event handler retains no inherent memory of how many pages have been printed, you must incorporate all logic for printing multiple pages into your event handler. 2. Explain how to use the Begin and End methods on a Web Service to make an asynchronous method call. Every public Web method on a Web Service can be called either synchronously or asynchronously. To make an asynchronous call to a Web method, you call the method named Begin<webmethod>, where <webmethod> is the name of the method. This method requires a delegate to an appropriate callback method and returns a value of IAsyncResult. This value is returned as a parameter in the callback method. To retrieve the data returned by the Web method, call End<webmethod>, supplying a reference to the IAsyncResult returned by Begin<webmethod>. This will allow you to retrieve the actual data returned by the Web method. 3. Briefly describe the five accessibility requirements of the Certified for Windows logo program. The five requirements are
o o

Support standard system settings. This requires your application to be able to conform to system settings for colors, fonts, and other UI elements. Be compatible with High Contrast mode. This requirement can be met by using only the System palette for UI colors. Provide documented keyboard access for all UI features. Key points in this requirement are shortcut keys and accessible documentation. Provide notification of the focus location. This requirement is handled primarily by the .NET Framework.

Convey no information by sound alone. This requirement can be met by providing redundant means of conveying information.

4. Explain how to use the HelpProvider component to provide help for UI elements. You can provide either a HelpString or a help topic for UI elements with the HelpProvider. The HelpProvider provides HelpString, HelpKeyWord, and HelpNavigator properties for each control on the form. If no value for the HelpProvider.HelpNameSpace is set, the HelpString will be provided as help. If the HelpNameSpace is set, the HelpProvider will display the appropriate help topic as configured by the HelpKeyWord and HelpNavigator properties. Help for a particular element is displayed when the element has the focus and the F1 key is pressed. 5. Describe how to create localized versions of a form. To create a localized version of a form, set the Localizable property to true. Then set the Language property to the language/region for which you want to create the localized form. Make any localization-related changes in the UI. The changed property values will automatically be stored in resource files and loaded when the CurrentUICulture is set to the appropriate CultureInfo. 6. Explain how to convert data in legacy code page formats to the Unicode format. You can use the Encoding.Convert method to convert data between encoding types. This method requires instances of both encoding types and an array of bytes that represents the data to be converted. It returns an array of bytes in the target format. You can convert a string or array of chars to an array of bytes with the Encoding.GetBytes method and can convert an array of bytes back to chars with the Encoding.GetChars method. 7. Explain the difference between Globalization and Localization. Globalization refers to the application of culture-specific format to existing data. Localization refers to providing new culture-specific resources and retrieving the appropriate resources based on the culture setting. 8. Explain how to use the PrintPreviewDialog control to display a preview of a printed document before it is printed. You display a preview of a printed document with the PrintPreviewDialog control by first setting the PrintDocument property of the PrintPreviewDialog instance to the PrintDocument you want to preview, then by calling the PrintPreviewDialog.Show command to display the dialog box. Chapter 9: Assemblies, Configuration, and Security

1. Describe how to sign your assembly with a strong name. Why would you want to do this? To sign your assembly with a strong name, you must have access to a key file or create one with the strong name utility (sn.exe). You then specify the key file in the AssemblyInfo file and verify that the version number is correct. The assembly will be signed with a strong name when built. In addition to identifying your assembly and ensuring version identity, a strong name is required if you want to install your assembly to the Global Assembly Cache. 2. Describe how to use code to retrieve resources at run time. You must first create an instance of the ResourceManager class that is associated with the assembly that contains the desired resource. You can then use the GetString method to retrieve string resources or the GetObject method to retrieve object resources. 3. Explain how to retrieve information from the configuration file at run time. How would you store information in the configuration file at design time? You must first create an instance of AppSettingsReader to read the configuration file. You can then call the GetValue method to read values represented in the configuration file. To add configuration file entries, you should create <add> elements in the <appSettings> node of the configuration file. In the <add> element, you should specify a value for the entry and a key that can be used to retrieve the entry. The value can be changed between executions of the application. 4. You are creating a solution that must be accessed by members of a group called Developers and Administrators on the local machine. Describe a plan to implement this security scheme. Create one PrincipalPermission that represents the Developers group and another PrincipalPermission that represents the BUILTIN\Administrators group. Then, create a third permission that represents the union of the two by calling the Union method and demand that permission. 5. Briefly highlight the differences between imperative and declarative security as they pertain to code access security. Imperative security is implemented by calling methods of Permission objects in code at run time. Declarative security is configured by attaching attributes representing permissions to classes and methods. Imperative security allows a finer control over the point in execution where permissions are demanded, but declarative security is emitted into metadata, and required permissions can be discovered through the classes in the System.Reflection namespace. Additionally,

you can request assembly-wide permissions using the Assembly (assembly) directive with declarative security. 6. What is a shared assembly? How would you create one? An assembly is an assembly of which only a single copy is installed per machine. This copy can be shared by multiple applications. To make an assembly a shared assembly, you must first assign it a strong name, and then install it to the global assembly cache. Chapter 10: Deploying Your Application 1. Describe XCOPY deployment. Under what conditions is it useful? When can it not be used? XCOPY deployment is a simple method of deployment where the DOS command XCOPY is used to copy the application directory and any subdirectories to the target machine. You can use XCOPY deployment if your application has no dependency on shared files and requires no special actions to be taken upon deployment. If an application requires a more complex deployment or references shared assemblies, you cannot use XCOPY. 2. You have created an application for a client who wants to distribute your application to his workforce via a network share. He wants to ensure that everyone who downloads the application will download it to the same folder. Describe a plan that would accomplish this goal. Create a setup project for the application. Using the User Interface Editor, provide a dialog box that allows the file directory to be set during administrative installation, but removes this box from regular installation. Use administrative installation to install the application to the network share. 3. You have written documentation for your application and have provided it in the form of several HTML files. Describe two ways you could include this content in your setup project. You can include loose HTML files along with your application by either including them when you create the setup project with the Setup wizard or by adding them to the project after creation with the File System Editor. 4. What is a native image? How do you create one? A native image is a precompiled version of a .NET assembly. You can create a native image of your application by using the Ngen.exe utility.

5. What is the purpose of a bootstrapper application? When do you not need to create one? A bootstrapper application automatically detects if Windows Installer is installed on the target machine. If Windows Installer is not present, it installs Windows Installer before proceeding with the rest of the installation. You should create a bootstrapper application unless all of your target machines are running Windows XP (which has Microsoft Windows Installer 1.5 already installed) or have had Microsoft Installer 1.5 installed previously. 6. Describe a general strategy for creating a setup project that terminates installation if a specific file is not already installed on the target machine. First, create a file search to search the file system for the specific file. Then create a launch condition to evaluate the results of the search. You can connect the launch condition to the results of the search by evaluating the value returned by the property specified in the searchs Property property in the expression specified by the launch conditions Condition property. 7. How would you ensure that all relevant registry entries were removed in the event that installation of your application failed? You can ensure that registry entries are removed, as well as perform any other clean-up tasks, by creating an Installer class and writing the appropriate code in the Rollback event handler. Then create a new Custom Action and set the InstallerClass, and EntryPoint properties to appropriate values. 34

Which one of the following tools is used to view the metadata information contained in a .NET assembly?
Select Answer: 1. al.exe 2. ilasm.exe 3. vbx.exe 4. csc.exe

5. ildasm.exe

1. What is the lifespan for items stored in ViewState?


Select Answer:

1. Item stored in ViewState exist for the life of the current page
2. Item stored in ViewState exist for the life of the current Session 3. Item stored in ViewState exist for the life of the current Applicaiton 4. Item stored in ViewState exist for the life of the current configuration

AS any web application works on request and response basis ,so on every post backs, The data in control gets lost. To retain page data on post backs, Asp.Net uses ViewState. It holds the data in hidden form fields and get fills the control with data. The life cycle of the view state exist for life of current running page only.

What si the difference between interface and abstractclass


Select Answer: 1. interface contain only methods 2. we can't declare a variable for interface 3. interface contain only events 4. None 5. All Ans : 2

The only Difference between Interface and Abstract class is we can declare a variable in abstract class but we can't declare in variable interface

How many types of Assemblies in .NET


Select Answer: 1. 1 2. 2 3. 3 4. 4 Ans : 2

There are Two Types of Assemblies in .Net those are 1)static Assemblie 2)DynamicAssemblie

Maximum How Many Non-Clustor Index Created per Table?


Select Answer: 1. 149 2. 249 3. 64 4. 128 Ans: 2

Data in ViewState is in Which Form??


Select Answer: 1. Binary 2. Encoded 3. Encrypted 4. Hex Form Ans: 2

How many types of polymorphism in C#


Select Answer: 1. 2 2. 4 3. 6 4. 3 Ans: 1

There is two type of polymorphism in c# the first one is runtime & second one is compiletime

If a method is marked as protected internal who can access it?


Select Answer: 1. Classes that are both in the same assembly and derived from the declaring class.

2. Only methods that are in the same class as the method in question. 3. Internal methods can be only be called using reflection. 4. Classes within the same assembly, and classes derived from the declaring class. Ans: 4

What are the two methods to move from one webform to another webform
Select Answer: 1. Response.Write(),Response.Close() 2. Response.Redirect(), Server.Transfer() 3. Server.Redirect(),Server.Transmit() 4. Response.Write(),Server.Transmit Ans: 2

What are Managed Providers in .NET


Select Answer: 1. OleDb,ODBC 2. SQL CLient,OraClient 3. Data Set,Data Adapter 4. DataList, DataGrid Ans: 2

Sql Client and OraClient are the Managed Providers. The memory management is by Common Language RunTime...

Is multiple inheritance supported by c#?


Select Answer: 1. Yes 2. No 3. Dont know Ans: 1

what is the command for listing all permission sets using caspol
Select Answer: 1. caspol -l 2. caspol -lp 3. caspol lg Ans: 2

which command for listing all code groups using caspol


Select Answer: 1. caspol -l 2. caspol -lg 3. caspol -lp Ans: 2

what are three policy in configuration files


Select Answer: 1. publisher policy,machine policy,enterprise policy 2. publisher policy,machine policy,user policy 3. enterprise policy,machine policy,user policy Ans: 1

WSDL is short form for


Select Answer: 1. Web Services Domain Language 2. Web Services Description Language 3. Web Services Document Language Ans: 2

Which transport protocol is used to call webservies?


Select Answer: 1. HTTP 2. SOAP 3. HTML 4. All the above Ans: 2

The process in which a web page sends data back to the same page on the server is called?
Select Answer: 1. PostBack 2. Session 3. Query strings 4. All the above Ans: 1 How to find the database table size? (With the System Stored procedure) and its syntax. Select Answer: 1. sp_spaceused 2. sp_usedspace 3. sp_space 4. sp_used

Ans : 1
Its shows the table name, and how many row the table contains, and the table size....

Where is an asp.net form always submitted?


Select Answer:

1. Always submitted to the same page itself 2. Always submitted to another page 3. Submitted either to the page itself or another page Ans: 1

What data type does the RangeValidator control support?


Select Answer: 1. Integer,String and Date. 2. char, integer and number 3. only number 4. only string Ans: 1

range validators are used to restrict the value

Name the namespace for working with Data specific to IBM DB2?
Select Answer: 1. IBM.Data.DB2 2. System.Data.DB2Client 3. System.Data.SQLClient 4. IBM.Data.IBMClient Ans: 1

IBM.Data.DB2 is the default namespace to be used whenever you are trying to connect directly to an IBM DB2 Database Server

what is the command for building the batch files in .Net Framework.
Select Answer: 1. NMake all

2. Build.bat 3. tlbimp.dll 4. filename.exe Ans: 2

It is used for building the batch files all at a time and output can be viewed given in msdn files.

What is diffrence between Int16,Int32,Int64 in C# ?


Select Answer: 1. Int16 for Short, Int32 for double,Int64 for Long 2. All are Same 3. In c# , Its new Feature 4. No One Ans: 1

how many types of inheritance is supported by c#


Select Answer: 1. 3 2. 4 3. 5 4. no one Ans: 1

How many types of JIT in present in ,Net


Select Answer: 1. 4 2. 3 3. 5 4. no one Ans: 2

I have triggers, views, functions, stored Procedures for a table when I am dropping that table what are the objects deleted?
Select Answer: 1. Trigger and stored procedure only deleted 2. Stored Procedure, trigger and Functions gets deleted 3. view, trigger gets deleted 4. functions only gets deleted 5. none will get deleted Ans: 3

If you have two DLL files, how would you differentiate that which DLL is belong to .Net
Select Answer: 1. Run Gacutil 2. Run DLL with TDF extension or RCW 3. Run Strong.exe 4. Run Gacutil and Strong.exe Ans: 2

We don't run dll file directly, if dll file is related with .net its tun by rcw or by tdf extension.

In how many ways we can pass parameters through function call in c#.net?
Select Answer: 1. 1 2. 2 3. 3

4. 4 Ans: 3

1. Pass by value 2. Pass by reference 3. Pass by using "out" keyword

Reflection reads information from the information store of assemblies Reflection reads information from the information store of assemblies does system .reflection store information about assemblies
Select Answer: 1. true 2. false 3. sometimes Ans: 1- true

The default type of enum is integer and has a default value 1


Select Answer: 1. true 2. false 3. sometimes Ans: 2- False

Unboxing of a null reference type will return a null.


Select Answer: 1. true 2. false 3. sometimes Ans: 1- True

what is the difference between CLS and CTS?


Select Answer: 1. Both are same 2. CLS is subset of CTS 3. CTS is subset of CLS 4. There is no difference between them Ans: 2

CLS is specific to a known language where as CTS is for all dotnet languagues. So some of elements which works for C# wont work for vb.net for example.

if the code is like this; byte a, b, c; a = 255; b = 122; c = (byte)(a & b); what will be the value of C?
Basic question in exams Select Answer: 1. 255 2. 122 3. 133 4. 377 5. none Ans: 1

byte denotes the smaller value among given integer.

Which of the following contains web application setup strings?


Select Answer: 1. app.config

2. web.config 3. assembly.config 4. machine.config 5. None of these Ans: 2

All the app setups, authentication, debug style is initialized in webconfig file in XML format.

Difference between Override and Overload?


Select Answer: 1. An abstract class without virtual function 2. An abstract class with virtual function 3. An Sealed class with virtual function 4. None of these Ans: 2

An overriding function should be a virtual function with override keyword.

Can you configure a .NET Remoting object via XML file?


Select Answer: 1. Yes 2. No 3. Yes sometimes possible 4. No relation Ans: 1

Yes, via machine.config and application level .config file (or web.config in ASP.NET). Applicationlevel XML settings take precedence over machine.config.

does c# support templates


Select Answer: 1. true 2. false

3. sometimes Ans: 2- False

Which concept is better to use - Remoting or Webservice for internet applications?


Select Answer: 1. Remoting 2. Webservice 3. Both has its own importance Ans: 2

Webservice is best to use for Internet applications and remoting for Intranet. Webserice accepts most of the protocols like HTTP and TCP. Remoting doesnt support TCP. Webservices are more secured. It can be used in many applications by placing in UDDI.

What is the advantage of materialised View?


Select Answer: 1. Performance improvement 2. Security 3. Momory saving 4. All of the above Ans: 1

OLTP Stands for?


Select Answer: 1. Online Transmit procession 2. Online Transaction Processing 3. Online Trasmit Protocol 4. Online Transaction Proramming Ans: 2

Online Transaction Processing (OLTP) relational databases are optimal for managing changing data. They typically have several users who are performing transactions at the same time that change real-time data. Although individual requests by users for data generally reference few rows, many of these requests are being made at the same time.

What's the maximum size of a row?


Select Answer: 1. 6080 bytes 2. 8060 bytes 3. 7000 bytes 4. 7080 bytes Ans: 2

RAID stands for


Select Answer: 1. Redundant Array of Inexpensive Disks 2. Recursive Array of Inexpensive Disks 3. Recursive Array of Integrated Disks 4. Redundant Array of Readonly Disks Ans: 1

which is not a validation control ?


Select Answer: 1. Required Field Validator 2. Compare Validator 3. Error Validator 4. Regular Expression Validator Ans: 3

there are 6 validators. 1.Required Field Validator 2.Compare Validator 3.Regular Expression Validator 4.Custom Control Validator 5.Range Validator

You ASP.NET application manages order entry data by using a DataSet object named orderEntry. The orderEntry object includes two DataTable objects named orderNames and OrderDetails. A ForeignKeyConstraint object named orderDetailsKey is defined between the two DataTable objects. You attempt to delete a row in orderNames while there are related rows in OrderDetails, and an exception is generated. What is the most likely cause of the problem?
Select Answer: 1. The current value of OrderDetails.KeyDeleteRule is Rule.Cacade 2. The current value of OrderDetails.KeyDeleteRule is Rule.SetNull 3. The current value of OrderDetails.KeyDeleteRule is Rule.SetDefault 4. The current value of OrderDetails.KeyDeleteRule is Rule.None Ans: 4

You create an ASP.NET application that contains confidential information. You use form-based authentication to validate users. You need to prevent unauthenticated users from accessing the application.
Select Answer: 1. Set a Page directive in the start page of your application to redirect users to a login page. 2. Set a Page directive in the start page of your application to disallow anonymous users 3. In the authorization section of the Machine.config file, set the users attribute of the allow element to "?". 4. In the authorization section of the Web.config file, set the users attribute of the deny element to "?". Ans: 4

Which one of the following is not present in .NET Framework 1.1


Select Answer: 1. Anonymous Methods 2. Multilevel Inheritance 3. Interface 4. Abstract Classes Ans: 1

Anonymous Methods are a new set of genre in .NET Framework 2.0

Which one of the following is new in .NET Framework 2.0


Select Answer: 1. Interfaces 2. Constants 3. Generics 4. Delegates Ans: 3

Generics are the new genre of types similar to the templates in C++. Generics are very useful in defining dynamic collection types.

How many generations are there in Garbage Collection


Select Answer: 1. 5 2. 3 3. 4 4. 2 Ans: 2
Garbage Collection happens in generations of 0,1 & 2 - totally three generations in which it collects objects in memory based on their usage and graph statistics

What is the core .NET Framework DLL


Select Answer: 1. mscoree.dl 2. mscorimp.dll 3. mscorwks.dll 4. mslibwks.dll Ans: 3

mscorwks.dll is the core .net dll which is the executing engine for .net applications

What are bubbled Events


Select Answer: 1. Events that are wrongly fired 2. Events that are not fired 3. Events that are fired from a control 4. Events that are fired from a parent control Ans: 4

DataGrid Command Buttons fire Bubbled Events which are useful in handling events generated from a row within multiple rows

what are the common properties in every validation control?


Select Answer: 1. ControlToValidate property 2. Text property 3. ControlToValidate property and Text property 4. None of the Above Ans: 3

Order of methods fired during the page load?


Select Answer: 1. Init,PreRender,Load,Unload 2. Init,Load,Unload,PreRender 3. Init,Load,PreRender,Unload 4. Init,PreRender,Unload,Load Ans: 3

What type of code is found in a Code-Behind class?


Select Answer: 1. Server 2. Client 3. Both(Server & Client) 4. None of the Above Ans: 1

Code Behind Class is used for server side coding

Biztalk: Which shape is used to catch exception in an Orchestration?


Select Answer: 1. Send 2. Decide 3. loop 4. Scope 5. Message assignment Ans: 4

What are prerequists of a .net language.


Select Answer: 1. CLS

2. CTS 3. CLR 4. Base class libraries 5. All Ans: 5

What are core components of SqlServer 2005


Select Answer: 1. Database Engine 2. Reporting Services 3. Analysis Services 4. SQL Server Integration Services 5. All of the above Ans: 5

What property do you have to set to tell the grid which page to go to when using the Pager object?
Select Answer: 1. DefaultPageIndex 2. CurrentPageIndex 3. CurrentIndex 4. CurrentPage Ans: 2

What are the different types of assemblies available ?


Select Answer: 1. Private 2. Public

3. Shared 4. Private,Public,Shared and Satellite Ans: 4

How many classes can a single .NET DLL contain?


Select Answer: 1. 5 2. 6 3. 10 4. many Ans: 4

What data types do the RangeValidator control support?


Select Answer: 1. Integer 2. String 3. Date 4. All the above Ans: 4

Which of these string definitions will prevent escaping on backslashes in C#?


Select Answer: 1. string s = #.n Test string.; 2. string s = ..n Test string.; 3. string s = @.n Test string.; 4. string s = .n Test string.; Ans: 3

In a database we can able to create more than one primary key is it possible indirectly?
I want to create 3 fields in one table as a primary key. is it possible indirectly Select Answer: 1. possible 2. not possible 3. cann't say 4. no chance Ans: 1

after creating one primary key, the other 2 fields are unique key with not null constraint

How to make a field as read only in a datagrid?


Suppose we want to make one field as read only and rest fields should get updated or deleted.How can we do it? Select Answer: 1. Cannot do this 2. Property Builder>> Bound Columns>>Read Only 3. We can work with all the fields simultaneously,cannot make updations in a particular field Ans: 2

Right Click on the datagrid and select property builder>> bound columns>>click read only check box

Security is very important on any web site. By default, a .Net web site is configured with which of the following authentication types?
Select Answer: 1. Windows Forms 2. Windows 2000 3. IIS Anonymous 4. Windows

Ans: 3

can we have protected element as a namespace member?


eg namespace mine { protected class test { } } Select Answer: 1. yes,all access specifiers are valid for namespace members 2. No,only private access specifiers are possible 3. No,implicitly all members are protected 4. No,the namespace allows only public and internal elements as its members. Ans: 4

Can we use access specifiers like public,private etc with namespace declaration?
Select Answer: 1. Yes,It is possible 2. Some times possible 3. No,because implicitly have public access 4. no,because implicitly have private access Ans: 3

What is the default join in SQL Server2000?


Select Answer: 1. outer join 2. inner join

3. equi join 4. left outer join Ans: 2

When ever you use DROP Table option in Sql server 2000 the indexes related to that table also deleted or not?
Select Answer: 1. No they remain in Database for future reference 2. Yes they get deleted along with table. 3. We can set the option as per our choice Ans: 2

Why cant you specify the accessibility modifier for methods inside the interface?
Select Answer: 1. They all are private 2. They all are public 3. They all are protected Ans: 2

Can multiple catch blocks be executed for a single try statement?


Select Answer: 1. Yes 2. Occasionally 3. No Ans: 3

Once the proper catch block processed, control is transferred to the finally block (if there are any).

What class is underneath the SortedList class?


Select Answer: 1. sorted Array 2. sorted HashTable 3. sorted Arraylist Ans: 2

How can you sort the elements of the array in descending order?
Select Answer: 1. By calling ReverseSort(); 2. By calling SortReverse() 3. By calling Descend() 4. By calling Sort() and then Reverse() methods. Ans: 4

All other functions doesnt exist in C#.

Whats 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 a

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.

You are a database developer for A Datum Corporation. You are creating a database that will store statistics for 15 different high school sports. 50 companies that publish sports information on their web sites will use this information. Each company's web site arranges and displays the statistics in a different format
You need to package the data for delivery to the companies. What should you do? Select Answer: 1. Extract the data by using SELECT statements that include the FOR XML clause 2. use the sp_makewebtask system stored procedure to generate HTML from the data returned by SELECT statements 3. create data transformation services packages that export the data from database and place the data into tab-delimited text files 4. create the application that uses SQL_DMO to extract the data from the database and transform the data into standard electronic data interchange (EDI)files Ans: 1

The data will be published at the company's website .XML is a markup language for documents containing structured information.XML is well suited to provide rich web documents.

What is Composite Custom Control


Select Answer: 1. HTML Controls 2. Web Controls 3. combination of existing HTML and Server Controls. Ans: 3

Combination of HTML and Web Controls (Server Controls) is called Composite Custom Controls. We are using Composite custom in asp.net

Which property on a Combo Box do you set with a column name, prior to setting the DataSource, to display data in the combo box?
Select Answer: 1. DataTextField property. 2. DataValueField Property 3. DataMember

Ans: 1

For Displaying Data in Combobox, we should set the DataTextField Property. For Setting Values for each Item, We should set DataValueField Property

The CLR handles registration at run time. True?


Select Answer: 1. True 2. Also at compile time 3. Also at design time 4. False Ans: 1- True

Which of the following incorrectly describe ASP.Net is?


Select Answer: 1. it is the most complete platform for developing Web applications for W2K 2. it is platform-independent 3. it is hosted under the latest IIS 4. it is hosted under all versions of IIS 5. Answer 2 & 4 Ans: 5

Can As statement with Catch statement in error handling be omitted?


Select Answer: 1. True 2. False Ans: 1- True

Which namespace will be included for using the MsgBox( ) of VB 6.0?


Select Answer: 1. Microsoft.VisualBasic.Message 2. Microsoft.VisualBasic.Interaction Ans: 2

can it possible to omit a parameter to a procedure that expects a ParamArray?


Select Answer: 1. True 2. False Ans: 2- False

Is it possible to use a function's name as local variable inside the procedure?


Select Answer: 1. False 2. True Ans: 2- True

Passing an array using ByRef or ByVal makes a difference if u use a ReDim statement inside the called procedure. Which array size will be affected?
Select Answer: 1. an array passed by ByVal 2. an array passed by ByRef 3. both affected 4. none affected Ans: 2

ParamArray arguments are passed by in a function?


Select Answer: 1. Always by value 2. Always by reference 3. both 4. none Ans: 1

In global.asax file which event will occur first when you invoke an application?
Select Answer: 1. Application_Start() 2. Session_Start() Ans: 1

What is difference between "tlbexp" and "Regasm" tools?


Select Answer: 1. Tlbexp will not register the type library unlike regasm. 2. Regasm will not register the type library unlike TlbExp 3. Regasm is used to create Rcw TlbExp is used to create CCw 4. TlbExe is used to create Rcw ,while Tlb Regasm is used to create CCw Ans: 1

Is a string a value type or a reference type ?


Select Answer: 1. value type

2. reference type 3. both 1& 2 Ans: 2

You use Visual Studio .NET to create a Windows-based application. The application enables users to update customer information that is stored in a database. Your application contains several text boxes. All TextBox controls are validated as soon as focus is transferred to another control. However, your validation code does not function as expected. To debug the application, you place the following line of code in the Enter event handler for the first text box: Trace.WriteLine(Enter); You repeat the proc
Select Answer: 1. Enter Validating TextChanged Leave Validated 2. Enter TextChanged Leave Validating Validated 3. Enter Validating Validated TextChanged Leave 4. Enter TextChanged Validating Validated Leave 5. Enter Validating TextChanged Validated Leave

Ans: 2

1. You use Visual Studio .NET to create an application. Your application contains two classes, Region and City, which are defined in the following code segment. (Line numbers are included for reference only) 01 public class Region { 02 public virtual void CalculateTax() { 03 // Code to calculate tax goes here. 04 } 05 } 06 public class City:Region { 07 public override void CalculateTax() { 08 // Insert new code. 09 } 10 } You need to add code to the CalculateTax method of the City class to call t
Select Answer: 1. CalculateTax(); 2. this.CalculateTax(); 3. base.CalculateTax(); 4. Region r = new Region();r.CalculateTax(); Ans: 3

What is the output of following C# code ?

class Rectangle { int length,breadth; Rectangle( int length,int breadth ) { this.length=length ; this.breadth=breadth ;

} static void Main( ) { Rectangle R1=new Rectangle( 3, 2 ) ; Rectangle R2 =new Rectangle( 1, 5 ) ; System.Console.WriteLine( R1 != R2 ) ; } static public bool operator!=( Rectangle r1, Rectangle r2 ) { return r1.length*r1.breadth != r2.length*r2.breadth ; }

Select Answer: 1. True 2. False 3. Error --> The operator operator '!=' requires a matching operator '==' to also be defined 4. Error --> Not possible to overload the operator '!=' 5. Error --> Access modifier 'public' should come before the modifier 'static' Ans: 3

What is the output of following C# code ?

using System; class MainClass {

static int aVar=10; static MainClass() { Console.Write(aVar); aVar=100; } static void Main() { MainClass.aVar = 3; Console.Write(MainClass.aVar); }

}
Select Answer: 1. 103 2. 310 3. 3 4. 1003 5. 3100

Ans: 1

What is the output of following C# code ?

using System ; class MainClass { static void Main( ) { string str1 = "String1" ; string str2 = "String2" ; str2 = str1 ; str1.Replace( 't','p' ) ; Console.WriteLine( "{0} {1}",str1, str2 ) ;

Select Answer: 1. String1 String1 2. Spring1 Spring1 3. Spring1 String1 4. 1, 2 & 3 are false Ans: 1

What is the output of following C# code ?

using System; class MainClass { static void Main( ) { string str = null ; if( str == "" ) Console.WriteLine( "true" ) ; else Console.WriteLine( "false" ) ; } }
Select Answer: 1. true 2. false 3. syntax error 4. NullReferenceException

Ans: 2

Correction Number 2 ......*** How HR can "Help" to resolve any .NET developer is professional or pirated software user ? ........... Make years 2 and 1 year respectively instead of 3 in all three options.
Correction Number 2 ......*** How HR can "Help" to resolve any .NET developer is professional or pirated software user ? Select Answer: 1. Correction Number 2 ......*** How HR can "Help" to resolve any .NET developer is professional or pir 2. Correction Number 2 ......*** How HR can "Help" to resolve any .NET developer is professional or pir 3. Correction Number 2 ......*** How HR can "Help" to resolve any .NET developer is professional or pir Ans: 1

**** Correction : .NET Garbedge Collector (GC) mark object as ? Make State , ........... not sate every place.
**** Correction : .NET Garbedge Collector (GC) mark object as ? Make State not sate every place. Select Answer: 1. **** Correction : .NET Garbedge Collector (GC) mark object as ? 2. **** Correction : .NET Garbedge Collector (GC) mark object as ? 3. **** Correction : .NET Garbedge Collector (GC) mark object as ? Ans: 1

what is managed and unmanaged code?


Select Answer: 1. managed code mean over the runtime control 2. unmanaged code out of the runtime control Ans: 1

Work Order of Garbedge Collector (GC) in .NET ?


Select Answer: 1. Mark -> Generation -> Compact -> Allocation 2. Compact-> Allocation -> Mark -> Generation 3. Generation -> Allocation -> Mark -> Compact 4. Allocation -> Mark -> Generation -> Compact 5. None Ans: 4

The C# keyword int maps to which .NET type?


Select Answer: 1. System.Int16 2. System.Int32 3. System.Int64 4. System.Int128 Ans: 2

Is it possible to restrict the scope of a field/method of a class to the classes in the same namespace?
Select Answer: 1. There is no way to 2. restrict to a namespace. Namespaces are never units of protection 3. But if youre using assemblies, you can use the internal 4. access modifier to restrict access to only within the assembly. Ans: 1

How do you implement thread synchronization (Object.Wait, Notify,and CriticalSection) in C#? Select Answer:

1. You want the lock statement, which is the same as Monitor Enter/Exit: 2. lock(obj) { // code } translates to 3. try {CriticalSection.Enter(obj); // code } 4. finally { CriticalSection.Exit(obj); 5. } Ans: 1

Is it possible to have different access modifiers on the get/set methods of a property?


Select Answer: 1. No. The access modifier on a 2. property applies to both its get and set accessors. 3. What you need to do if you want them to be different is make the property read 4. only (by only providing a get accessor) and create a private/internal 5. set method that is separate from the property Ans: 1

How do you specify a custom attribute for the entire assembly (rather than for a class)?
Select Answer: 1. Global attributes must appear 2. after any top-level using clauses and before the first type or namespace declarations 3. An example of this is as follows: 4. using System; 5. [assembly : MyAttributeClass] class X {} Ans: 1

How do I simulate optional parameters to COM calls?


Select Answer: 1. You must use the Missing class 2. and pass Missing.Value (in System.Reflection) 3. for any values that 4. have optional parameters. Ans: 1

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?
Select Answer: 1. You should declare the variable as an int, but when you pass it in you must specify it as out, lik 2. the following: int i; foo(out i); 3. where foo is declared as follows: [return-type] 4. foo(out int o) { } Ans: 1

What are the default user directory permissions when a Web site is created in IIS?
Select Answer: 1. Read and Execute 2. Read and Write 3. Read/Write and Execute 4. Execute Only Ans: 1

An application using cookie authentication was working fine on another server. When moved to a new server, cookie authentication is not working correctly. Which one of the following is the likely explanation of the above problem?
Select Answer: 1. The new IIS server is not configured to allow anonymous access 2. SSL is not properly configured. 3. The IP address of the new server does not match the prior server IP address 4. Passport authentication is not correctly configured. 5. The users are not correctly entering their passwords. Ans: 1

How to create class for holding data?


Classes for holding data The following are the main classes used to hold data in Ado.NET: DataSet DataTable DataRow A DataSet is an in-memory representation of the database. DataSet contains DataTables (and more...) DataTable represents a database table DataTable contains DataRows (and more...) A DataRow represents a record in a database table. DataRow is a collection of all fields in a record. Select Answer: 1. The following are the main classes used to hold data in Ado.NET: 2. DataSet 3. DataRow 4. DataTable 5. DataRow Ans: 1

Event handling in .NET is handled by which feature


Select Answer: 1. Reflection 2. Remoting 3. Delegates 4. web service Ans: 3

What is the value for i? int i = 0; while(i++ <10) ; Console.WriteLine("i = " + i);
Select Answer: 1. Compile Error 2. Runtime Error 3. 10 4. 11 5. None of the above Ans: 4