Sunteți pe pagina 1din 23

1. How many types of JIT compilers are available? There are Two types of JIT compilers.

standard JIT compiler. EconoJIT compiler. 2.What are the different types of assemblies name them? Private Public/Shared Satellite assembly 3.What is GAC? What are the steps to be taken to pick up the latest version from GAC? This Global Assembly Cache(GAC) stores .NET assemblies to be shared by several applications on that computer.publisher policy file is the configuration file to redirect to different version 1. Create the publisher Policy assembly using the assembly linker 2. Add the publisher policy assembly to the GAC using GACutil tool Gacutil /i 3. During runtime CLR is looking into the publisher policy file and redirect the application to bind with new version assembly as specified inside the publisher policy.

4.How do we use different versions of private assemblies in same application without re-build? In Asseblyinfo file need specify assembly version. assembly: AssemblyVersion 5.Different methods of using a legacy COM component in .NET framework? 1. TLBIMP to create an Assembly from a COM component 2. Reference a COM component directly from .NET Editor 6.How do you implement SSL? 1. create certificate request [ =>Right click on the website (VD) =>Click Directory Security Tab and click Server Certificate => Type name of certificate , Organization name , server name location info, => Type the path need to save certificate information Submit certificate request. ] 7.What is ref parameter? What is out parameter? Ref Parameter: Used to pass a parameter as a reference so that the function called will set the value. This could be used to return more than 1 value by a function. e.g. public int AddMuliply( int a , int b, ref int c) { c = a*b; return ( a+b); } The above function, returns the addition of two numbers as well as computes the multiplication result and passes to the calling function. Out Parameter: Used to pass values from the aspx Code-behind to the aspx page. The difference is that for a ref parameter, you have to assign a value before you call the function, while for OUT parameter, you dont have to assign a value, the calling function assumes that the called function would assign some value. A ref parameter must first be initialized before being passed from the calling function to the called function. but a out parameter need not be initialized, we can pass it directly when we pass a parameter as ref to a method, the method refers to the same variable and changes made will affect the actual variable. even the variable passed as out parameter is same as ref parameter, but implementation in c# is different, Arguement passed as ref parameter must be initialized before it is passed to the method. But in case of out parameter it is not necessary. But after a call to a method as out parameter it is necessary to initialize. When to use out and ref parameter, out parameter is used when we want to return more than one value from a method. Ref parameter can be used as both input and o/p parameter out parameter can be used as only output parameter 8.What is boxing? What is the benefits and disadvantages? Boxing is converting a value-type to reference type. An example is converting an integer value to an object value. Ex: int intValue = 10; object obj = (object)intValue; This is used if you want to pass variables of object types to certain functions or methods you have created. Commonly used in events for example (Object sender...). 9.Why multiple Inheritance is not possible in C#? Multple inheritance is coneceptually wrong. It shouldn't be allowed in any language. Inheritance is the strongest relationship that can be expressed in OO languages. It's used to express IS-A relationship. Aggregation is used to express IS CONSTRUCTED IN TERMS OF. If you're using multiple inheritance in C++ then you're design is wrong and you probably want to use aggregation. On the other hand it's plausible to want to use multiple interfaces. For instance you might have a class wheel and a class engine. You could say that your class car inherits from wheel and from engine but that's wrong. In fact car aggregates wheel and engine because it is built in terms of those classes. If wheel is an interface and engine is an interface then car must inherit both of these interfaces since it must implement the functionaity of wheel and engine .On this basis we can see that multiple inheritance for classes should not be allowed because it promotes mis-use of the strong IS-A relationship. C# enforces the correct concepts whilst C++ allows mis-use. multiple interface inheritance is permissible and C# allows this. It's all to do with properly understanding OO concepts. Absolute Multiple Inheritance is not possible in c# but partially it supports multiple inheritance by the use of Interfaces. As interfaces force a class to implement same type of behaviour (as defined in interface) which classes implements that interface What is the top .NET class that everything is derived from? System.Objects What is an abstract class? The abstract modifier can be used with classes, methods, properties, indexers, and events. Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes. Abstract classes have the following features: An abstract class cannot be instantiated.

An abstract class may contain abstract methods and accessors. It is not possible to modify an abstract class with the sealed modifier, which means that the class cannot be inherited. A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors. Use the abstract modifier in a method or property declaration to indicate that the method or property does not contain implementation. Abstract methods have the following features: An abstract method is implicitly a virtual method. Abstract method declarations are only permitted in abstract classes. Because an abstract method declaration provides no actual implementation, there is no method body; the method declaration simply ends with a semicolon and there are no braces ({ }) following the signature. For example: public abstract void MyMethod(); ________________________________________ abstract class is a prototype of a class. it is used to provide partial class implementation. abstract class contain abstract method which can be implemented by derived class. some rules for abstract class are following-: 1) an object of an abstract class can never be created. 2)you can not declare an abstract method outside the abstract class. 3)can not be declared sealed. WHAT IS THE ADVANTAGE OF SERIALIZATION? Serialization is the process of maintaing object in the form stream. it is useful in case of remoting. Serialization is the process of converting object into byte stream which is useful to transport object(i.e remoting),persisting object(i.e files,database) SERIALIZATION IS PROCESS OF LOADING THE OBJECT STATE IN THE FORM OF BYTE STREAMS IN DATABASE/FILE SYATEM. Can we inherit the java class in C# class,how? Java Programming language is not supported with .Net Framework hence you cannot inherit javaclass in C# class.Also Java has JavaByte code after compiling similar to MSIL which is similar but cannot inherit due to framework support. Are C# destructors the same as C++ destructors? No. They look the same but they are very different. The C# destructor syntax (with the familiar ~ character) is just syntactic sugar for an override of the System.Object Finalize method. This Finalize method is called by the garbage collector when it determines that an object is no longer referenced, before it frees the memory associated with the object. So far this sounds like a C++ destructor. The difference is that the garbage collector makes no guarantees about when this procedure happens. Indeed, the algorithm employed by the CLR garbage collector means that it may be a long time after the application has finished with the object. This lack of certainty is often termed non-deterministic finalization, and it means that C# destructors are not suitable for releasing scarce resources such as database connections, file handles etc. To achieve deterministic destruction, a class must offer a method to be used for the purpose. The standard approach is for the class to implement the IDisposable interface. The user of the object must call theDispose() method when it has finished with the object. C# offers the using construct to make this easier. What is wrapper class? is it available in c#? Wrapper Classes are the classes that wrap up the primitive values in to a class that offer utility method to access it . For eg you can store list of int values in a vector class and access the class. Also the methods are static and hence you can use them without creating an instance . The values are immutable . wrapper class are those class in which we can not define and call all predefined function .it is possible in java not C#. Which tool is used to browse the classes, structs, interfaces etc. in the BCL? wincv as in Windows Class View How is the using() pattern useful? What is IDisposable? How does it support deterministic finalization? The using() pattern is useful because it ensures that Dispose() will always be called when a disposable object (defined as one that implements IDisposable, and thus the Dispose() method) goes out of scope, even if it does so by an exception being thrown, and thus that resources are always released. What happens when a C# project has more than 1 Main methods f the project is compiled using /main switch with the compiler then the project compiles successfully. For example: class A { public static void Main(string[] args) { Console.WriteLine("Main in class A"); } } class B { public static void Main(string[] args) { Console.WriteLine("Main in class B"); } } Now compile with the /main switch with the C# compiler like csc MultipleMain.cs /main:A This will compile without error and while executing it will show Main in class A Attempting to compile an application consisting of multiple classes with defined Main methods and not specifying the /main switch will result in a compiler error. How do you refer parent classes in C#? A) Super B) This C) Base This keyword is used for reffering current object and Base keyword is used for referring parrent class. so ans. is C. Super: Super is used to Refer the Base Class in JAVA This: This is used to Refer the Current or Child Class in C# Base: Base is used to Refer The Parent or Base Class What is object pooling Defination: A performance optimization based on using collections of pre-allocated resources, such as objects or database connections With the advent of the .NET platform, writing code that pools objects and threads has become a simple task. By using the Threading and Collections namespaces, you can create robust object pooling applications. This could also be done by implementing COM+ interop interfaces into your code. Which method is actually called ultimately when Console.WriteLine( ) is invoked? A) Append( )

B) AppendFormat( ) C) Tostring( ) Ans: B, AppendFormat() method is called. What is an Assembly? An assembly is a file that is automatically generated by the compiler upon successful compilation of every .NET application. It can be either a Dynamic Link Library or an executable file. It is generated only once for an application and upon each subsequent compilation the assembly gets updated. The entire process will run in the background of your application; there is no need for you to learn deeply about assemblies. However, a basic knowledge about this topic will help you to understand the architecture behind a .NET application. An assembly is used by the .NET CLR (Common Language Runtime) as the smallest unit for: deployment; version control; security; type grouping and code reuse. Assemblies consists of a manifest and one or more modules and/or files like HTML, XML, images, video clips,... An assembly can be thought of as a logical DLL and must contain a single manifest and may optionally contain type meta data, MSIL ( Microsoft Intermediate Language) and resources. Assemblies come in 2 flavors: application private and shared. Application private assemblies are used by one application only. This is the default style of assembly. Such assemblies must reside in the application folder. Shared assemblies are meant to be used by more than one application. They must have a globally unique name and must be defined in the GAC (Global Assembly Cache). To learn more about viewing the GAC Basically there are two kind of assemblies when it comes to deployment. Private Assemblies Shared Assemblies Private assemblies are the ones which are in your application folder itself. They can be easily and uniquely identified by their name. These type of assemblies can be deployed simply by copying them to the bin folder of your application. Shared Assemblies are those which can be shared by multiple applications on the machine. For this we have to place the Shared assembly in the GAC. Now since we can install any application or assembly created by any company, that is we install assemblies from oracle, microsoft and similarly from many other companies. There is always a possiblity that they may use the same assembly name as your assembly name. If such type of assemblies are placed in the GAC then we cannot uniquely identify a particular assembly.But if we give a strong name to the assmebly then it is like a unique identifier for the assembly.It is Globally unique. Strong name consists of 1. Name of the assembly 2. Public key token 3. optionally any resources 4. Version Number So basically to uniquely identify a particular assembly from the GAC we have to give it a strong name. Its that simple. The Shared assembly can be deployed in to GAC by using the GACUTIL tool with the -i switch gacutil -i assemblyname or simply copying it to the assembly folder in the windows directory (XP) or WINNT directory(others) Also there are Satellite Assemblies which contian only resources like strings, images etc. Also there are dynamic assemblies which are generated on the fly dynamically. What does the modifier protected internal in C# mean? The Protected Internal can be accessed by Members of the Assembly or the inheriting class, and of course, within the class itself. In VB.NET, the equivalent of protected internal is protected friend. The access of this modifier is limited to the current assembly or the types derived from the defining class in the current assembly. To know more on different types of access specifiers Can multiple data types be stored in System.Array? So whats an array all about? An array is a collection of items of the same type, that is grouped together and encompassed within an array object. The array object, or the System.Array object to be precise, is derived from the System.Object class. It is thus, stored in the form of a heap in the memory.

An array may be of single dimensional, multi-dimensional or jagged (a jagged array means an array within an array). A group of items when assigned values within braces implicitly derive from System.Array class. See example below written in C#... int[] testIntArray = new int[4] { 2, 3, 4, 5 }; Object[] testObjArray = new Object[5] { 32, 22, 23, 69, 75 }; Ideally an array should contain a single data type. But still in case there is a requirement to place data of different data types in a specific array, then in such a scenario, the data elements should be declared as an object type. When this is done, then each element may point ultimately to a different data type. See code example below written in VB.NET... Dim allTypes As Object() = New Object() {} 'In this kind of scenario, the performance may tend to slow down, as data conversions may take place. 'In case a value type is converted to reference type, then boxing and unboxing occurs 'To know more on Value Types & Reference Types, Click Here Dim studentTable(2) As Object studendTable(0) = "Vishal Khanna" studentTable(1) = 28 studentTable(2) = #9/1/1978# 'To get these values of these varying datatypes, their values are converted to their original data type Dim myAge As Integer = CInt(studentTable(1)) Dim myBirthDay as Date = CDate(studentTable(2)) How to sort array elements in descending order in C#? Elements of an array may not be sorted by default. To sort them in descending order, the Sort() method is first called. Next, to descend the order, call the Reverse()

method Whats the use of "throw" keyword in C#? The throw keyword is used to throw an exception programatically in C#. In .NET, there is an in-built technique to manage & throw exceptions. In C#, there are 3 keyword, that are used to implement the Exception Handling. These are the try, catch and finally keywords. In case an exception has to be implicitly thrown, then the throw keyword is used. See code example below, for throwing an exception programatically... class SomeClass { public static void Main() { try { throw new DivideByZeroException("Invalid Division Occured"); } catch(DivideByZeroException e) { Console.WriteLine("Exception - Divide by Zero" ); } } } Can we put multiple catch blocks in a single try statement in C#? Yes. Multiple catch blocks may be put in a try block. See code example below, to see multiple catch blocks being used in C#. class ClassA { public static void Main() { int y = 0; try { val = 100/y; Console.WriteLine("Line not executed"); } catch(DivideByZeroException ex) { Console.WriteLine("DivideByZeroException" ); } catch(Exception ex) { Console.WritLine("Some Exception" ); } finally { Console.WriteLine("This Finally Line gets executed always"); } Console.WriteLine("Result is {0}",val); } } How to achieve polymorphism in C#? In C#, polymorphism may be achieved by overloading a function, overloading an operator, changing the order of types, changing the types using the same name for the member in context. To see some code examples of polymorphism, Click Here. What is polymorphism? Polymorphism means allowing a single definition to be used with different types of data (specifically, different classes of objects). For example, a polymorphic function definition can replace several type-specific ones, and a single polymorphic operator can act in expressions of various types. Many programming languages implement some forms of polymorphism. The concept of polymorphism applies to data types in addition to functions. A function that can evaluate to and be applied to values of different types is known as a polymorphic function. A data type that contains elements of different types is known as a polymorphic data type. Polymorphism may be achieved by overloading a function, overloading an operator, changing the order of types, changing the types using the same name for the member in context. Example: Public Class Calc { public void fnMultiply(int x, int y) { return x * y; } public void fnMultiply(int x, int y, int z) { return x * y * z; } } ... ... Calc obj; int Result; Result = obj.fnMultiply(2,3,4); // The second fnMultiply would be called Result = obj.fnMultiply(3,4); // The first fnMultiply would be called //Here, the call depends on the number of parameters passed, polymorphism is achieved using overloading How to add a ReadOnly property in C#? Property - A property is an entity that describes the features of an object. A property is a piece of data contained within a class that has an exposed interface for reading/writing. Looking at that definition, you might think you could declare a public variable in a class and call it a property. While this assumption is somewhat valid, the true technical term for a public variable in a class is a field. The key difference between a field and a property is in the inclusion of an interface. We make use of Get and Set keywords while working with properties. We prefix the variables used within this code block with an underscore. Value is a keyword, that holds the value which is being retrieved or set. See code below to set a property as ReadOnly. If a property does not have a set accessor, it becomes a ReadOnly property. public class ClassA {

private int length = 0; public ClassA(int propVal) { length = propVal; } public int length { get { return length; } } } How to prevent a class from being inherited? Sealed in C#? In order to prevent a class in C# from being inherited, the sealed keyword is used. Thus a sealed class may not serve as a base class of any other class. It is also obvious that a sealed class cannot be an abstract class. Code below... sealed class ClassA { public int x; public int y; } No class can inherit from ClassA defined above. Instances of ClassA may be created and its members may then be accessed, but nothing like the code below is possible... class DerivedClass: ClassA {} // Error Can we inherit multiple interfaces in C#? Yes. Multiple interfaces may be inherited in C#. Note that when a class and multiple interfaces are to be inherited, then the class name should be written first, followed by the names of the interfaces. See code example below, on how to inherit multiple interfaces in C#. class someclass : parentclass, IInterface1, IInterface2 { //...Some code in C# } What are the different ways of overloading methods in C#? What is function overloading in C#? Before knowing the different methods of overloading in C#, lets first clear out what exactly overloading is. Overloading is the OOPs concept of using a method or a class in different styles by modifying the signature of the parameters in it. To know more on overloading, Click Here. In order to achieve overloading, there may be several techniques applied. There are different types of overloading like Operator Overloading, Function Overloading etc. Function overloading may be achieved by changing the order of parameters in a function, by changing the types passed in the function, and also by changing the number of parameters passed in a function. See code sample below to see types of overloading. //Define a method below public void fnProcess(int x, double y) { ...... } //change the order of parameters public void fnProcess(double x, int y) { //.......Some code in C# } //Similarly, we may change the number of parameters in fnProcess //and alter its behaviour How to call a specific base constructor in C#? What is a Constructor? - It is a method that gets invoked when an instance of a class is created. In case a class has plenty of constructors, i.e. there are plenty of overloaded constructors, in such a scenario, it is still possible to invoke a specific base constructor. But there is a special way, as explicit calls to a base constructor is not possible in C#. See code below: public class dotnetClass { public dotnetClass() { // The constructor method here } // Write the class members here } //Sample code below shows how to overload a constructor public class dotnetClass { public dotnetClass() { // This constructor is without a parameter // Constructor #1 } public dotnetClass(string name) { // This constructor has 1 parameter. // Constructor #2

} } This constructor gets executed when an object of this class is instantiated. This is possible in C#. Calling a specific constructor will depend on how many parameters, and what parameters match a specific constructor. Note that a compile time error may get generated when 2 constructors of the same signature are created. We may make use of the this keyword and invoke a constructor. See code example below. this("some dotnet string"); //This will call Constructor #2 above What is the use of the base keyword. Suppose we have a derived class named dotnetderivedclass. If this derived class is to invoke the constructor of a base class, we make use of the base keyword. See code example below on how to use a base keyword to invoke the base class constructor. public class dotnetClass { public dotnetClass() { // The 1st base class constructor defined here } public dotnetClass(string Name) { // The 2nd base class constructor defined here } } public class dotnetderivedclass : dotnetClass // A class is being inherited out here { public dotnetderivedclass() { // dotnetderivedclass 1st constructor defined here } public dotnetderivedclass(string name):base(name) { // dotnetderivedclass 2nd constructor defined here } } Note that we have used the base keyword in the sample code above. The sequence of execution of the constructors will be as follows: public dotnetClass() method -> public dotnetderivedclass() method The above sequence triggers when there is no initializer to the base class, and thus it triggers the parameterless base class constructor. The other base class constructor may also get invoked when we pass a parameter while defining it. What is a static constructor? Static Constructor - It is a special type of constructor, introduced with C#. It gets called before the creation of the first object of a class(probably at the time of loading an assembly). See example below. Example: public class SomeClass() { static SomeClass() { //Static members may be accessed from here //Code for Initialization } } While creating a static constructor, a few things need to be kept in mind: * There is no access modifier require to define a static constructor * There may be only one static constructor in a class * The static constructor may not have any parameters * This constructor may only access the static members of the class * We may create more than one static constructor for a class Can a class be created without a constructor? No. In case we dont define the constructor, the class will access the no-argument constructor from its base class. The compiler will make this happen during compilation. What are generics in C#? Generics in C# is a new innovative feature through which classes and methods in C# may be designed in such a way that the rules of a type are not followed until it is declared. The generics feature in C# has been introduced with version 2.0 of the .NET Framework. Using generics, a class template may be declared that may follow any type as required at runtime. The class behavior is later governed by the type that we pass to the class. Once the type is passed, the class behaves depending on the type passed to this generic class. Collection of C#.NET Interview Questions,C#.NET FAQs,C#.NET Realtime Interview Questions and Answers ,Microsoft C# Interview Questions What is the use of the main() function in C#? Every executable C# application must contain a class defining a Main() method that signifies the entry point of the application. Note that the Main() method is of the access type public by nature. Moreover, it is also static. See example below: using System; class Question { public static int Main(string[] args) { Console.Writeline("Another Question"); Console.Readline(); return 0;

} } A public member is accessible from other types. The main() method is set as static so that it may be invoked at class level itself, without the need of creating an instance of it. The single parameter is an array of strings. that may contain any number of incoming command line arguments. Can we set the specifier of the main() method in C# as private? Yes. When the access specifier is set as private for the Main() method, then other assemblies may not invoke this class' Main() method as the starting point of the application. The startup scope gets limited to the class in context itself. See code below: private static void Main() { //This code isn't invoked automatically by other assemblies } Can we set different types of parameters & return-types in main() method"? Yes. The Main() method may easily be played around with by developers by passing different parameters and setting different return types. See the code below, that demonstrates different ways the Main() method may be implemented: (1) public static void Main(string[] args) { //NO return type, the argument is an array of strings } (2) public static int Main(string[] args) { //Return type is int, argument is an array of strings } (3) public static int Main() { //Return type is int, NO arguments } (4) public static void Main() { //Return type is void, NO arguments } What is the use of GetCommandLineArgs() method? The GetCommandLineArgs() method is used to access the command line arguments. The return value of this method is an array of strings. It is a method of the System.Environment class. See the code example below: public static int Main(string[] args) { string[] strArgs = System.Environment.GetCommandLineArgs(); Console.WriteLine("Arguments {0}", strArgs[0]); } What is the use of System.Environment class? The class System.Environment is used to retrieve information about the operating system. Some of the static members of this class are as follows: 1) Environment.OSVersion - Gets the version of the operating system 2) Environment.GetLogicalDrives() - method that returns the drives 3) Environment.Version - returns the .NET version running the application 4) Environment.MachineName - Gets name of the current machine 5) Environment.Newline - Gets the newline symbol for the environment 6) Environment.ProcessorCount - returns number of processors on current machine 7) Environment.SystemDirectory - returns complete path to the System Directory 8) Environment.UserName - returns name of the entity that invoked the application Why is the new keyword used for instantiating an object in .NET? The new keyword instructs the .NET compiler to instantiate a new object, with appropriate number of bytes (depending on the type) for the object and gather required memory from the managed heap. What are the default values for bool, int, double, string, char, reference-type variables? When the objects of the following types are declared, then they have a default value during declaration. The following table shows the default value for each type: Type Default Value bool false int 0 double 0 string null char '\0' Reference Type null How to declare a constant variable in C#? What is the use of the const keyword? If a variable needs to have a fixed value, that may not be changed across the application's life, then it may be declared with the const keyword. The value assigned to a constant variable (using the const keyword) must be known at the time of compilation In C#, can we create an object of reference type using const keyword? No. A constant member may not be created of an object that is of reference type, because its value is decided dynamically at runtime. What is the difference between const and readonly in C#? When using the const keyword to set a constant variable, the value needs to be set at compile time. The const keyword may not be used with an object of reference type. In case a reference type needs to be assigned a non-changeable value, it may be set as readonly What are the different parameter modifiers available in C#?

What is a parameter modifier? Parameter modifiers in C# are entities that controls the behaviour of the arguments passed in a method. Following are the different parameter modifiers in C#: 1) None - if there is NO parameter modifier with an argument, it is passed by value, where the method recieves a copy of the original data. 2) out - argument is passed by reference. The argument marked with "out" modifier needs to be assigned a value within this function, otherwise a compiler error is returned. public void multiply(int a, int b, out int prod) { prod = a * b; } Here, note that prod is assigned a value. If not done so, then a compile time error is returned. 3) params- This modifier gives the permission to set a variable number of identical datatype arguments. Note that a method may have only one "params" modifier. The params modifier needs to be in the last argument. static int totalruns(params int[] runs) { int score = 0; for(int x=0; x &nsbp;score+=runs[x]; return score; } Further, from the calling function, we may pass the scores of each batsman as below... score = totalruns(12,36,0,5,83,25,26); 4) ref - The argument is given a value by the caller, where data is passed by reference. This value may optionally be reset in the called method. Note that even if NO value is set in the called method for the ref attribute, no compiler error is raised. What is the difference between out and ref in C#? 1) out parameters return compiler error if they are not assigned a value in the method. Not such with ref parameters. 2) out parameters need not be initialized before passing to the method, whereas ref parameters need to have an initial value before they are passed to a method. What is delay signing? Delay signing allows you to place a shared assembly in the GAC by signing the assembly with just the public key. This allows the assembly to be signed with the private key at a later stage, when the development process is complete and the component or assembly is ready to be deployed. This process enables developers to work with shared assemblies as if they were strongly named, and it secures the private key of the signature from being accessed at different stages of development. Is there an equivalent of exit() for quitting a C# .NET application? Yes, you can use System.Environment.Exit(int exitCode) to exit the application or Application.Exit() if it's a Windows Forms app. Can you prevent your class from being inherited and becoming a base class for some other classes? Yes, that is what keyword sealed in the class definition is for. The developer trying to derive from your class will get a message: cannot inherit from Sealed class WhateverBaseClassName. It is the same concept as final class in Java. If a base class has a bunch of overloaded constructors, and an inherited class has another bunch of overloaded constructors, can you enforce a call from an inherited constructor to an arbitrary base constructor? Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class. I was trying to use an "out int" parameter in one of my functions. How should I declare the variable that I am passing to it? You should declare the variable as an int, but when you pass it in you must specify it as 'out', like the following: int i; foo(out i); where foo is declared as follows: [return-type] foo(out int o) { } How do I make a DLL in C#? You need to use the /target:library compiler option. Is XML case-sensitive? Yes, so and are different elements. How do I simulate optional parameters to COM calls? You must use the Missing class and pass Missing.Value (in System.Reflection) for any values that have optional parameters. Will finally block get executed if the exception had not occurred? Yes. What is the C# equivalent of C++ catch (), which was a catch-all statement for any possible exception? Does C# support try-catch-finally blocks? Yes. Try-catch-finally blocks are supported by the C# compiler. Here's an example of a try-catch-finally block: using System; public class TryTest { static void Main() { try { Console.WriteLine("In Try block"); throw new ArgumentException(); } catch(ArgumentException n1) { Console.WriteLine("Catch Block"); } finally { Console.WriteLine("Finally Block"); } } }

Output: In Try Block Catch Block Finally Block If I return out of a try/finally in C#, does the code in the finally-clause run? Yes. The code in the finally always runs. If you return out of the try block, or even if you do a "goto" out of the try, the finally block always runs, as shown in the following example: using System; class main { public static void Main() { try { Console.WriteLine("In Try block"); return; } finally { Console.WriteLine("In Finally block"); } } } Both "In Try block" and "In Finally block" will be displayed. Whether the return is in the try block or after the try-finally block, performance is not affected either way. The compiler treats it as if the return were outside the try block anyway. If it's a return without an expression (as it is above), the IL emitted is identical whether the return is inside or outside of the try. If the return has an expression, there's an extra store/load of the value of the expression (since it has to be computed within the try block). Is there a way to force garbage collection? Yes. Set all references to null and then call System.GC.Collect(). If you need to have some objects destructed, and System.GC.Collect() doesn't seem to be doing it for you, you can force finalizers to be run by setting all the references to the object to null and then calling System.GC.RunFinalizers(). Is there regular expression (regex) support available to C# developers? Yes. The .NET class libraries provide support for regular expressions. Look at the documentation for the System.Text.RegularExpressions namespace. Does C# support properties of array types? Yes. Here's a simple example: using System; class Class1 { private string[] MyField; public string[] MyProperty { get { return MyField; } set { MyField = value; } } } class MainClass { public static int Main(string[] args) { Class1 c = new Class1(); string[] arr = new string[] {"apple", "banana"}; c.MyProperty = arr; Console.WriteLine(c.MyProperty[0]); // "apple" return 0; } } What connections does Microsoft SQL Server support? Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and passwords) 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. Why would you use untrusted verification? Web Services might use it, as well as non-Windows applications. How is method overriding different from overloading? When overriding, you change the method behavior for a derived class. Overloading simply involves having a method with the same name within the class. What is the implicit name of the parameter that gets passed into the class set method? Value, and its datatype depends on whatever variable we are changing. How do I register my code for use by classic COM clients? Use the regasm.exe utility to generate a type library (if needed) and the necessary entries in the Windows Registry to make a class available to classic COM clients. Once a class is registered in the Windows Registry with regasm.exe, a COM client can use the class as though it were a COM class

Can we use static constructors to initialize non static members? Yes, it is possible.But we have to create an object of the class inside the static constructor and then initialize the non static member through the object reference. Code(example):

class Class2 { int a; static Class2() { Class2 p = new Class2(); p.a = 45; System.Console.WriteLine(p.a); } static void Main() { } } Is MSIL a high/low/middle level language? MSIL Microsoft Intermediate Language: It is a set of CPU independent instructions which represent your code and used to provide language interoperability and compatibility of your code on different platforms. It is not a high level language: High Level language is C#: High level language is more human readable,closer to a spoken language. (Example: programming constructs like loops,if else conditions, keywords like using, class) High level language defines modular programming,OOPS concepts and the source code. MSIL is not low level language either: low level language is in an executable or binary format(eg: machine language) MSIL is not in an executable or binary format. MSIL is not middle level language too: Middle level language is C. It has modular programming and source code. It is human readable. C also supports low level programming (Assembly Language). Difference between Assembly.LoadFrom() and Assembly.LoadFile() methods? Both methods are used to load the assemblies. we can then extract all the metatdata of the assembly using Reflection. Difference: 1)LoadFrom can use either the name or the path of the assembly, LoadFile will expect the path of the assembly(see the overloaded versions) 2)LoadFrom uses a probing algorithm to find the assembly.f if you have two assemblies that have the same identity but different locations, you can get some unexpected behavior.But using LoadFile, you can load the desired assembly as needed. Can you install multiple assemblies together? Yes, we can install multiple assemblies together use installutil command example: installutil Assembly1.exe Assembly2.exe. It will install both the Assemblies in a transactional manner. if installation of one of the assemblies fail, the installation of the other assembly will be rolled back. How can you store decimals data precisely from .NET? NOTE: This is objective type question, Please click question title for correct answer. How can you write to a File System? NOTE: This is objective type question, Please click question title for correct answer. Difference between lock and Monitor.Enter() lock keyword basically provides a shortcut to Enter method of Monitor class. Monitor is used to provide thread synchronization.It means till the Thread in which the method is being used finishes its task, no other thread can access the object. example:

lock (object) { } It is compiled into Monitor.Enter(object); try { //code } finally { Monitor.Exit(object); } See the MSIL of the assembly. We can write much more code and perform customization in the try block. What is context menu? The menu that you get when you right-click is called the context menu. It is a modular piece of markup code that can move around the page. It consists of two distinct blocks, one is the user interface and another is the script code to connect the UI to it. Explain how to retrieve resources using ResourceManager class? ResourceManager class is used to retrieve resources at run time. Create a ResourceManager with resource file name and the resource assembly as parameters. After having created, you can use ResourceManager.GetString method to retrieve a string. Use the ResourceManager.GetObject method to retrieve images and objects from a resource file. What are the ways to retain variables between requests? Below there are different ways to retain variables between requests. That is: Context.Handler: This object can be used to retrieve public members of the webform from a subsequent web page. Querystring: Querystring is used to pass information between requests as part of the web address. Since it is visible to use, we can't use it to send any secured data. Cookies: Cookies stores small amount of information on client side. But we can't reply on cookies since many clients can refuse cookies. View state: View state stores items added to the pages. These properties are as hidden fields on the page. Session state: Session state stores items that are local to the current session. Application state: Application state stores items that are available to all users of the application. In .NET, which namespace contains classes used to a)Create a localized application? b)Develop Web Forms? c)Create Web server controls? d)Access Sql Server? e)Read a File? a)System.Globalization, System.Resources b)System.Web c)System.Web.UI.WebControls d)System.Data.SqlClient e)System.IO What is break mode? What are the options to step through code? Break mode lets you to observe code line to line in order to locate error. The VS.NET provides following options to step through code. Step Into Step Over Step Out Run To Cursor Set Next Statement How do we step through code? Stepping through the code is a way of debugging the code in which one line is executed at a time. There are three commands for stepping through code: Step Into: This debugging mode is usually time-consuming. However, if one wants to go through the entire code then this can be used. When you step into at a point and a function call is made somewhere in the code, then step into mode would transfer the control to the first line of the code of the called function. Step Over: The time consumed by the Step into mode can be avoided in the step over mode. In this, while you are debugging some function and you come across another function call inside it, then that particular function is executed and the control is returned to the calling function. Step Out: You can Use Step Out when you are inside a function call and want to return to the calling function. Step Out resumes execution of your code until the function returns, and then breaks at the return point in the calling function. What are the debugging windows available? The windows which are available while debugging are known as debugging windows.

These are: Breakpoints, Output, Watch, Autos, Local, Immediate, Call Stacks, Threads, Modules, Processes, Memory, Disassembly and Registers. Explain the similarities and differences between arrays and collections? The Array class is not part of the System.Collections namespace. But an array is a collection, as it is based on the list i nterface. Array has a fixed capacity but the classes in the System.Collections namespace dont have fixed capacity. Thats why array is a static container, but collection is dynamic container. Collections objects have a key associated with them. You can directly access an item in the collection by the key. But to f ind a specific item in an array, unless you dont know the index number you need to traverse the array to find the value. Explain declarative and imperative security? Security checks can be applied in two ways that is imperatively or declaratively. Declarative security is applied by associating attribute declarations that specify a security action with classes or methods. Imperative security is applied by calling the appropriate methods of a Permission object that represents the Principal (for role based security) or system resource (for code access security). What is code security? What are the types? .NET framework provides the security features to secure code from unauthorized users. There are two types of code security: Role based security: This authorizes user. Code access security: This protects system resources from unauthorized calls. Define Principal object? The Principal object represents authenticated users. It contains information about users identity and role. You have Princip al Permission object in .NET Framework that specifies user and its role. It has Demand method that checks the current user or Principal against the name and role specified in the Principal Permission. Which namespace contains the classes that required to serialize an object? Explain Object Serialization? System.Runtime.Serialization Object serialization is the process of reducing an object instance into a format that can be either stored to disk or transported over a network. Accenture DotNet Interview Questions and Answers What event can you subscribe to if you want to display information from SQL Print statements? NOTE: This is objective type question, Please click question title for correct answer. Q1. Explain the differences between Server-side and Client-side code? Ans. Server side code will execute at server (where the website is hosted) end, & all the business logic will execute at server end where as client side code will execute at client side (usually written in javascript, vbscript, jscript) at browser end. Q2. What type of code (server or client) is found in a Code-Behind class? Ans. Server side code. Q3. How to make sure that value is entered in an asp:Textbox control? Ans. Use a RequiredFieldValidator control. Q4. Which property of a validation control is used to associate it with a server control on that page? Ans. ControlToValidate property. Q5. How would you implement inheritance using VB.NET & C#? Ans. C# Derived Class : Baseclass VB.NEt : Derived Class Inherits Baseclass

Q6. Which method is invoked on the DataAdapter control to load the generated dataset with data? Ans. Fill() method.

Q7. What method is used to explicitly kill a user's session? Ans. Session.Abandon()

Q8. What property within the asp:gridview control is changed to bind columns manually? Ans. Autogenerated columns is set to false Q9. Which method is used to redirect the user to another page without performing a round trip to the client? Ans. Server.Transfer method.

Q10. How do we use different versions of private assemblies in same application without re-build? Ans.Inside the Assemblyinfo.cs or Assemblyinfo.vb file, we need to specify assembly version. assembly: AssemblyVersion Difference between VB.NET and C#. Difference between VB.NET and C#. VB.NET : ----------1)no unsigned int 2)Loosely typed language 3)no operator overloading

4)no pointers 5)no auto XML documentation

C#.net : ------------1) supports unsigned int 2)strongly typed language 3)supports operator overloading 4)supports pointers 5)supports auto XML documentation Name a feature which is common to all .NET languages? Name a feature which is common to all .NET languages? There is only one feature which is common to all languages and that is Garbage collection or GC. This feature is automated which relieves developers of much work. This garbage is disposed only when there is need of memory or stress for memory. GC feature halts the application for few seconds before restarting it. What is the difference between Master- Detail view and MVG? Following are the main advantages:1) MVG Makes effective use of the space. 2) Multiple set of detail records can be viewed from a single view If I write System.exit (0); at the end of the try block, will the finally block still execute ? No in this case the finally block will not execute because when you say System.exit (0); the control immediately goes out of the program, and thus finally never executes. whats the similarilty & difference between .dll extension and .exe extension files? A standard exe application is one that is created using Standard EXE project. It is the most widely used Project type using VB6. Standard EXE application is normally the most widely used among the available Project types in Visual Basic. Stand-alone programs have an .EXE file extension. Usage A standard EXE application is normally used when you want to develop a stand-alone application. Examples include calculators, text editors, and other similar applications. An ActiveX EXE application is one that is created using ActiveX EXE project. ActiveX EXE are widely used in conjunction with standard EXE applications. There are three types of widely used of ActiveX projects. These are: a. ActiveX EXE b. ActiveX DLL c. ActiveX Control ActiveX EXE: Unlike a stand-alone EXE file, an ActiveX EXE file is designed to work as an OLE server, which is nothing more than a program designed to share information with another program. It has an .EXE file extension. ActiveX DLL: ActiveX DLL files are not meant to be used by themselves. Instead, these types of files contain subprograms designed to function as building blocks when creating a stand-alone program. It has a .DLL file extension. ActiveX Control: Unlike an ActiveX DLL or ActiveX EXE file, an ActiveX Control file usually provides both subprograms and a user interface that you can reuse in other programs. It has an .OCX file extension. Usage 1. The ActiveX EXE/DLL is normally used when you need to build a component that is separate from the main program. The concept is based on COM model. 2. ActiveX DLL/EXE allows multiple applications to share the same code. This allows for scalability of programs, and saves time because you only need to write the code once. 3. ActiveX DLLs and ActiveX EXEs are almost same in the ways they are built and used. In either case, you build one or more classes that applications can use to do something. 4. One of the main differences between ActiveX EXE and an ActiveX DLL's is that the code is executed within the main program's address space for ActiveX DLL. This is because the code lies inside the program's address space, calling methods and execution of code is very fast. Differences An ActiveX Exe provides the reusability of code, by accessing it from different clients. An ActiveX Exe is a component that can be called by another application by providing a reference to the component. But a Standard Exe application cannot be called in this way. An ActiveX EXE's code is run in a separate process. When the main program calls an ActiveX EXE's method, the application passes required parameters into the ActiveX EXE's and calls the method. The ActiveX EXE, upon execution may return the results to the main program. This is slower than running an ActiveX DLL's method inside the main program's address space. What is strong name? A name that consists of an assembly's identityits simple text name, version number, and culture information (if provided) strengthened by a public key and a digital signature generated over the assembly. What is managed code and managed data? We can describe this Manage code like, if a code running under the control CLR, then we can call it as Managed Code. Managed code is code that is written to target the services of the common language runtime (see what is CLR?). In order to target these services, the code must provide a minimum level of information (metadata) to the runtime. All C# (when not using the unsafe keyword), Visual Basic .NET, J#, and JScript .NET code is managed by default. Visual Studio .NET C++ code is not managed by default, but the compiler can produce managed code by specifying a Command-line switch (/CLR). Closely related to managed code is managed data data that is allocated and reallocated by the common language runtime's garbage collector. C#, Visual Basic.NET, J# and JScript .NET data is managed by default. C# data can, however, be marked as unmanaged through the use of special keywords. Visual Studio .NET C++ data is unmanaged by default (even when using the /CLR switch), but when using Managed Extensions for C++, a class can be marked as managed by using the __gc keyword. As the name suggests, this means that the memory for instances of the class is managed by the garbage collector. In addition, the class becomes a full participating member of the .NET Framework community, with all of the benefits and restrictions that brings. An example of a benefit is proper interoperability with classes written in other languages (for example, a managed C++ class can inherit from a Visual Basic.NET class). An example of a restriction is that a managed class can only inherit from

one base class. Any restrictions, such as this one, are designed to prevent common programming errors. What is the Microsoft Intermediate Language (MSIL)? MSIL is the Machine independent Code into which .NET Framework programs are compiled. It contains instructions for loading, storing, initializing, and calling methods on objects. Combined with metadata and the common type system, MSIL allows for true cross language integration. Prior to execution, MSIL is converted to machine code via CLRs Just-in-Time (JIT) compiler. What is the common type system (CTS)? The common type system (CTS) is a rich type system, built into the common language runtime (CLR) that supports the types and operations found in most of .NET programming languages. The common type system supports the complete implementation of a wide range of programming languages. What is the common language runtime (CLR)? The common language runtime (CLR) is major component in the .NET Framework and it is the execution engine for .NET Framework applications. It is responsible for proving the number of services, including the following: 1. Code management (loading and execution) 2. Verification of type safety 3. Conversion of Microsoft Intermediate Language (MSIL) to native code 4. Access to metadata (enhanced type information) 5. Managing memory for managed objects 6. Enforcement of code access security (See what is code access security?) 7. Exception handling, including cross-language exceptions 8. Interoperation between managed code, COM objects, and pre-existing DLLs (unmanaged code and data) 9. Automation of object layout 10. Support for developer services (profiling, debugging, and so on) What is GC in NET Framework? The .NET Framework's garbage collector manages the allocation and release of memory for your application. Each time you use the new operator to create an object, the runtime allocates memory for the object from the managed heap. As long as address space is available in the managed heap, the runtime continues to allocate space for new objects. However, memory is not infinite. Eventually the garbage collector must perform a collection in order to free some memory. The garbage collector's optimizing engine determines the best time to perform a collection, based upon the allocations being made. When the garbage collector performs a collection, it checks for objects in the managed heap that are no longer being used by the application and performs the necessary operations to reclaim their memory. From the following which datatype is not supported in RangeValidator? What does the "EnableViewState" property do? Why would I want it on or off? It allows the page to save the users input on a form across postbacks. It saves the server-side values for a given control into ViewState, which is stored as a hidden value on the page before sending the page to the clients browser. When the page is posted back to the server the server control is recreated with the state stored in viewstate. What is the Global.asax used for? The Global.asax (including the Global.asax.cs file) is used to implement application and session level events. Whats the difference between Response.Write() andResponse.Output.Write()? Response.Output.Write() allows you to write formatted output. What is the Difference between Web.config and Machine.config? Scope: Web.config => For particular application in IIS. Machine.config = > For All the applications in IIS Created: Web.config => Created when you create an application Machine.config => Create when you install Visual Studio Known as: Web.config => is known as Application Level configuration file Machine.config => is known as Machine level configuration file Location: Web.config => In your application Directory Machine.config => \Microsoft.NET\Framework\(Version)\ CONFIG Advantages of Crystal Reports Advantages of Crystal Reports Some of the major advantages of using Crystal Reports are: 1. Rapid report development since the designer interface would ease the coding work for the programmer. 2. Can extend it to complicated reports with interactive charts and enhance the understanding of the business model 3. Exposes a report object model, can interact with other controls on the ASP.NET Web form 4. Can programmatically export the reports into widely used formats like .pdf, .doc, .xls, .html and .rtf

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. C#.NET Interview Questions and Answers on Exception Handling,Error Handling and Runtime Type Information 1 Can I use exceptions in C#? Yes, in fact exceptions are the recommended error-handling mechanism in C# (and in .NET in general). Most of the .NET framework classes use exceptions to signal errors. 2 What types of object can I throw as exceptions? Only instances of the System.Exception classes, or classes derived from System.Exception. This is in sharp contrast with C++ where instances of almost any type can be thrown. 3 Can I define my own exceptions? Yes, just derive your exception class from System.Exception. 4 Does the System.Exception class have any cool features? Yes - the feature which stands out is the StackTrace property. This provides a call stack which records where the exception was thrown from. For example, the following code: using System; class CApp { public static void Main() { try { f(); } catch( Exception e ) { Console.WriteLine( "System.Exception stack trace = \n{0}", e.StackTrace ); } } static void f() { throw new Exception( "f went pear-shaped" ); } } produces this output: System.Exception stack trace = at CApp.f() at CApp.Main() Note, however, that this stack trace was produced from a debug build. A release build may optimise away some of the method calls which could mean that the call stack isn't quite what you expect. 5 When should I throw an exception? This is the subject of some debate, and is partly a matter of taste. However, it is accepted by many that exceptions should be thrown only when an 'unexpected' error occurs. How do you decide if an error is expected or unexpected? This is a judgement call, but a straightforward example of an expected error is failing to read from a file because the seek pointer is at the end of the file, whereas an example of an unexpected error is failing to allocate memory from the heap. 6 Does C# have a 'throws' clause? No, unlike Java, C# does not require (or even allow) the developer to specify the exceptions that a method can throw. Run-time Type Information 7 How can I check the type of an object at runtime? You can use the is keyword. For example: using System; class CApp { public static void Main() { string s = "fred"; long i = 10; Console.WriteLine( "{0} is {1}an integer", s, (IsInteger(s) ? "" : "not ") ); Console.WriteLine( "{0} is {1}an integer", i, (IsInteger(i) ? "" : "not ") ); } static bool IsInteger( object obj ) { if( obj is int obj is long ) return true; else return false; } } produces the output:

fred is not an integer 10 is an integer 8 Can I get the name of a type at runtime? Yes, use the GetType method of the object class (which all types inherit from). For example: using System; class CTest { class CApp { public static void Main() { long i = 10; CTest ctest = new CTest(); DisplayTypeInfo( ctest ); DisplayTypeInfo( i ); } static void DisplayTypeInfo( object obj ) { Console.WriteLine( "Type name = {0}, full type name = {1}", obj.GetType(), obj.GetType().FullName ); } } } produces the following output: Type name = CTest, full type name = CTest Type name = Int64, full type name = System.Int64 Method and Property ,Events and Delegates,Debugging and Testing Interview 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. 7. Whats a delegate? A delegate object encapsulates a reference to a method. 8. Whats a multicast delegate? A delegate that has multiple handlers assigned to it. Each assigned handler (method) is called. Debugging and Testing 1. What debugging tools come with the .NET SDK? 1. CorDBG command-line debugger. To use CorDbg, you must compile the original C# file using the /debug switch. 2. DbgCLR graphic debugger. Visual Studio .NET uses the DbgCLR. 2. What does assert() method do? In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true. 3. 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. Microsoft C# Interview Questions on Class and Struct Concept,Interfaces,Questions on Abstract and Sealed Class Members 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. Whats the .NET collection class that allows an element to be accessed using a unique key? HashTable. What class is underneath the SortedList class? A sorted HashTable. Will the finally block get executed if an exception has not occurred? Yes. 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 {}. Explain the three services model commonly know as a three-tier application. Presentation (UI), Business (logic and underlying code) and Data (from storage or other sources). When do you absolutely have to declare a class as abstract? 1. When the class itself is inherited from an abstract class, but not all base abstract methods have been overridden. 2. When at least one of the methods in the class is abstract. What is an interface class? Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes. Why cant you specify the accessibility modifier for methods inside the interface? They all must be public, and are therefore public by default. What happens if you inherit multiple interfaces and they have conflicting method names? Its up to you to implement the method inside your own class, so implementation is left entirely up to you. T his 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 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. What is the difference between a Struct and a Class? Struts are value-type variables and are thus saved on the stack, additional overhead but faster retrieval. Another difference is that struts cannot inherit. 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. What does the keyword virtual declare for a method or property? The method or property can be overridden. How is method overriding different from method overloading? When overriding a method, you change the behavior of the method for the derived class. Overloading a method simply involves having another method with the same

name within the class. Can you declare an override method to be static if the original method is not static? No. The signature of the virtual method must remain the same. (Note: Only the keyword virtual is changed to keyword override) What are the different ways a method can be overloaded? Different parameter data types, different number of parameters, different order of parameters. If a base class has a number of overloaded constructors, and an inheriting class has a number of overloaded constructors; can you enforce a call from an inherited constructor to a specific base constructor? Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class. Whats a delegate? A delegate object encapsulates a reference to a method. Whats a multicast delegate? A delegate that has multiple handlers assigned to it. Each assigned handler (method) is called. Why are there five tracing levels in System.Diagnostics.TraceSwitcher? The tracing dumps can be quite verbose. For applications that are constantly running you run the risk of overloading the machine and the hard drive. Five levels range from None to Verbose, allowing you to fine-tune the tracing activities. Where is the output of TextWriterTraceListener redirected? To the Console or a text file depending on the parameter passed to the constructor. How do you debug an ASP.NET Web application? Attach the aspnet_wp.exe process to the DbgClr debugger. What are three test cases you should go through in unit testing? 1. Positive test cases (correct data, correct output). 2. Negative test cases (broken or missing data, proper handling). 3. Exception test cases (exceptions are thrown and caught properly). Can you change the value of a variable while debugging a C# application? Yes. If you are debugging via Visual Studio.NET, just go to Immediate window. What is the role of the DataReader class in ADO.NET connections? It returns a read-only, forward-only rowset from the data source. A DataReader provides fast access when a forward-only sequential read is needed.What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET? SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix. OLE-DB.NET is a .NET layer on top of the OLE layer, so its not as fastest and efficient as SqlServer.NET. 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. 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. What connections does Microsoft SQL Server support? Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and password). Between Windows Authentication and SQL Server Authentication, which one is trusted and which one is untrusted? Windows Authentication is trusted because the username and password are checked with the Active Directory, the SQL Server authentication is untrusted, since SQL Server is the only verifier participating in the transaction. What does the Initial Catalog parameter define in the connection string? The database name to connect to. What does the Dispose method do with the connection object? Deletes it from the memory. How is the DLL Hell problem solved in .NET? Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly. What are the ways to deploy an assembly? An MSI installer, a CAB archive, and XCOPY command. What namespaces are necessary to create a localized application? System.Globalization and System.Resources. What is the smallest unit of execution in .NET? An Assembly. When should you call the garbage collector in .NET? As a good rule, you should not call the garbage collector. However, you could call the garbage collector when you are done using a large object (or set of objects) to force the garbage collector to dispose of those very large objects from memory. However, this is usually not a good practice. How do you convert a value-type to a reference-type? Use Boxing. What are Namespaces? A) Naming convention used in .Net

B) Group of classes categorized to avoid name clash C) None of the above C. None of the above A Namespace in .Net is like containers of objects. They may contain unions, classes, structures, interfaces, enumerators and delegates. Main goal of using namespace in .Net is for creating a hierarchical organization of program. In this case a developer does not need to worry about the naming conflicts of classes, functions, variables etc., inside a project. What are Indexers? What is the use of it, and when to use it An indexer is a member that enables an object to be indexed in the same way as an array. There are times when it is desirable to access a collection within a class as though the class itself were an array. For example, suppose you create a list box control named myListBox that contains alist of strings stored in a one-dimensional array, a private member variable named myStrings. Alist box control contains member properties and methods in addition to its array of strings.However, it would be convenient to be able to access the list box array with an index, just as if thelist box were an array. This can be achieved using the Indexer What is difference between dispose() & finalize() If you want to delete resources(objects) those are not using ,you should not worry about that, garbage collecter implicitly call finalize() method and remove all such object but if you want to delete object forcefully.The larger object ,you want to delete after completeing task),than you can explicitly calldispose() method. Design Pattern : If your classes use unmanaged resources, you need to implement both Dispose & Finalize. Dispose() is called by user code, that is, the code that is using your class. Finalize/Destructor cannot be called by User code, it's called by Garbage Collector Finalize : Is a destructor, called by Garbage Collector when the object goes out of scope. Implement it when you have unmanaged resources in your code, and want to make sure that these resources are freed when the Garbage collection happens. Dispose : Same purpose as finalize, to free unmanaged resources. However, implement this when you are writing a custom class, that will be used by other users. Overriding Dispose() provides a way for the user code to free the unmanaged objects in your custom class. As an aside, here's how the GC works: The garbage collector keeps track of objects that have Finalize methods, using an internal structure called the finalization queue. Each time your application creates an object that has a Finalize method, the garbage collector places an entry in the finalization queue that points to that object. The finalization queue contains entries for all the objects in the managed heap that need to have their finalization code called before the garbage collector can reclaim their memory. Implementing Finalize methods or destructors can have a negative impact on performance and you should avoid using them unnecessarily. Reclaiming the memory used by objects with Finalize methods requires at least two garbage collections. When the garbage collector performs a collection, it reclaims the memory for inaccessible objects without finalizers. At this time, it cannot collect the inaccessible objects that do have finalizers. Instead, it removes the entries for these objects from the finalization queue and places them in a list of objects marked as ready for finalization. Entries in this list point to the objects in the managed heap that are ready to have their finalization code called. The garbage collector calls the Finalize methods for the objects in this list and then removes the entries from the list. A future garbage collection will determine that the finalized objects are truly garbage because they are no longer pointed to by entries in the list of objects marked as ready for finalization. In this future garbage collection, the objects' memory is actually reclaimed. Dispose() is called by the user of an object to indicate that he is finished with it, enabling that object to release any unmanaged resources it holds. Finalize() is called by the run-time to allow an object which has not had Dispose() called on it to do the same. However Dispose() operates determinalistically, whereas there is no guarantee that Finalize() will be called immediately when an object goes out of scope - or indeed at all, if the program ends before that object is GCed - and as such Dispose() is generally preferred. In which scenerio we use interfaces, abstract and concrete class? Which one is better and appropriate? Differentiate these three terms in depth. The decision tree for this is pretty detailed. :) In most cases, using an abstract class is the "right" thing to do if you're trying to create a common class from which others will derive and which isn't fully specified. Interfaces are nice if you don't want to force classes to have a single root class in their hierarchy, as a single class can implement multiple interfaces. Concrete classes should be used if it's fully specified--i.e. subclasses don't have any hooks into which they must provide functionality. Interface - used to define a skeleton. Classes who want to confirm to that skeleton implementsts the interface Abstract class - Use abstract class when you want to provide some functionality to the user and at the same time would like to enforce some skeleton (structure) for the users of your class Concrete class - Use a concrete class to represent an object (data & methods) which can be extended or reused. Use following guidelines for each of the abstractions: Interface: -- If your child classes should all implement a certain group of methods/functionalities, but each of the child classes is free to provide its own implementation, then use interfaces. For e.g., if you are implementing a class hierarchy for vehicles, implement an interface called "Vehicle", which has properties like Colour, MaxSpeed etc., and methods like Drive(). All child classes like "Car", "Scooter", "AirPlane", "SolarCar" etc. should derive from this base interface, but provide a seperate implementation of the methods and properties exposed by Vehicle. -- If you want your child classes to implement multiple, unrelated functionalities, in short multiple inheritance, use interfaces. For e.g., if you are implementing a class called "SpaceShip", that has to have functionalities from a "Vehicle", as well as that from a "UFO", then make both "Vehicle" and "UFO" as interfaces, and then create a class "SpaceShip" that implements both "Vehicle" and "UFO". Abstract Classes -- When you have a requirement where your base class should provide default implementation of certain methods, whereas other methods should be open to being overridden by child classes, use abstract classes. For e.g., again take the example of the "Vehicle" class above. If we want all classes deriving from "Vehicle" to implement the "Drive()" method in a fixed way, whereas the other methods can be overridden by child classes. In such a scenario, we implement the "Vehicle" class as an abstract class with an implementation of "Drive", while leave the other methods / properties as abstract so they could be overridden by child classes. -- The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share. For example, a class library may define an abstract class that is used as a parameter to many of its functions, and require programmers using that library to provide their own implementation of the class by creating a derived class. What is the difference between Abstract and Interface? Answer In an interface class, all methods are abstract - there is no implementation. In an abstract class some methods can be concrete - there can be implementation. In an interface class, no accessibility modifiers are allowed - are public by default. In an abstract class accessibility modifiers are allowed. Abstract Class: 1. Abstract Class Can contain Abstract Methods and Non-Abstract Methods. 2. When a Non-Abstract Class is Inherited from an Abstract Class, the Non-Abstract Class should provide all the implementations for the inherited Abstract Method. Interface: 1. Interface is nothing but Pure Abstract Class ie Interface can contain only the function declaration. 2. All the members of the interface are Public by Default and you cannot provide any access modifiers. 3. When a class is inherited from the interface, the inherited class should provide actual implementations for the inherited members.

What is the main difference between pointer and delegate with examples? Delegates in c# are very similar to function pointers in c++ the only difference is that delegates are type safe due to these are CLR targated under .net framework, while function pointers in c++ are not type safe. A Delegate in c# allows to pass a method of class to object of other class. Rules in Deligation:1. In order to create a Delegate a Signature(parameter) must match Signature of object. 2. Define all the methods which has the same Signature as Deligate define. 3. Create the deligate object & pass the method as a parameter to Deligate. 4. Now call the encapsulated method using deligated object. The best example of Deligation model is ADO.NET Architecture & Event Handling in windows environment. Simply say Delegate is a strongly typed function pointer and pointer holds reference to a variable or pointer is a variable which holds the address of another variable. Delegate to function--- is same as---- pointer to object. Delegates are function pointers. They are used when the function which needs to be called is not know at compile time. Pointers, on the other hand, are used to point to variables or object references in unsafe code. What is managed code?Skill/Topic: Intermediate A) Code managed ouside the IL B) Code which can't be managed by the IL C) Code written in VB.NET D) Code to be compiled by IL D) is the correct choice. Managed code is the code written in one of 20 high level programming languages available for use with .Net framework which is compiled into IL during the first level of compilation. Ans : (A) The managed code are the code which are managed by the CLR not by the executalble code itself.(Ref.- MCSD Training Kit Developing Web Applicaion of PHI) A is correct ans, Ex: vbc compiler is compile to vb.net application in to MSIL(IL) code csc compiler is compile to c#.net application code in to MSIL code DotNet support multiple languages , each compiler will convert MSIL(IL) Code only. after CLR execute the code in memory before taking code in CLR, JIt will compile machine understandble code. How does one compare strings in C#? In the past, you had to call .ToString() on the strings when using the == or != operators to compare the strings' values. That will still work, but the C# compiler now automatically compares the values instead of the references when the == or != operators are used on string types. If you actually do want to compare references, it can be done as follows: if ((object) str1 == (object) str2) { ... } Here's an example showing how string compares work: using System; public class StringTest { public static void Main(string[] args) { Object nullObj = null; Object realObj = new StringTest(); int i = 10; Console.WriteLine("Null Object is [" + nullObj + "]n" + "Real Object is [" + realObj + "]n" + "i is [" + i + "]n"); // Show string equality operators string str1 = "foo"; string str2 = "bar"; string str3 = "bar"; Console.WriteLine("{0} == {1} ? {2}", str1, str2, str1 == str2 ); Console.WriteLine("{0} == {1} ? {2}", str2, str3, str2 == str3 ); }} Output: Null Object is [] Real Object is [StringTest] i is [10] foo == bar ? False bar == bar ? True 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. How do I get deterministic finalization in C#? In a garbage collected environment, it's impossible to get true determinism. However, a design pattern that we recommend is implementing IDisposable on any class that contains a critical resource. Whenever this class is consumed, it may be placed in a using statement, as shown in the following example: using(FileStream myFile = File.Open(@"c:temptest.txt", FileMode.Open)) { int fileOffset = 0; while(fileOffset <> { Console.Write((char)myFile.ReadByte()); fileOffset++; }} When myFile leaves the lexical scope of the using, its dispose method will be called. How can I get around scope problems in a try/catch? If you try to instantiate the class inside the try, it'll be out of scope when you try to access it from the catch block. A way to get around this is to do the following: Connection conn = null; try { conn = new Connection(); conn.Open(); }

finally { if (conn != null) conn.Close(); } By setting it to null before the try block, you avoid getting the CS0165 error (Use of possibly unassigned local variable 'conn'). Why do I get an error (CS1006) when trying to declare a method without specifying a return type? If you leave off the return type on a method declaration, the compiler thinks you are trying to declare a constructor. So if you are trying to declare a method that returns nothing, use void. The following is an example: // This results in a CS1006 error public static staticMethod (mainStatic obj) // This will work as wanted public static void staticMethod (mainStatic obj) How do I convert a string to an int in C#? Here's an example: using System; class StringToInt { public static void Main() { String s = "105"; int x = Convert.ToInt32(s); Console.WriteLine(x); }} How do you directly call a native function exported from a DLL? Here's a quick example of the DllImport attribute in action: using System.Runtime.InteropServices; class C { [DllImport("user32.dll")] public static extern int MessageBoxA(int h, string m, string c, int type); public static int Main() { return MessageBoxA(0, "Hello World!", "Caption", 0); }} This example shows the minimum requirements for declaring a C# method that is implemented in a native DLL. The method C.MessageBoxA() is declared with the static and external modifiers, and has the DllImport attribute, which tells the compiler that the implementation comes from the user32.dll, using the default name of MessageBoxA. For more information, look at the Platform Invoke tutorial in the documentation. What is the .NET datatype that allows the retrieval of data by a unique key? HashTable. How do you specify a custom attribute for the entire assembly (rather than for a class)? Global attributes must appear after any top-level using clauses and before the first type or namespace declarations. An example of this is as follows: using System; [assembly : MyAttributeClass] class X {} Note that in an IDE-created project, by convention, these attributes are placed in AssemblyInfo.cs.

My switch statement works differently! Why? C# does not support an explicit fall through for case blocks. The following code is not legal and will not compile in C#: switch(x) { case 0: // do something case 1: // do something in common with 0 default: // do something in common with //0, 1 and everything else break; } To achieve the same effect in C#, the code must be modified as shown below (notice how the control flows are explicit): class Test { public static void Main() { int x = 3; switch(x) { case 0: // do something goto case 1; case 1: // do something in common with 0 goto default; default: // do something in common with 0, 1, and anything else break; }}} How can I access the registry from C# code? By using the Registry and RegistryKey classes in Microsoft.Win32, you can easily access the registry. The following is a sample that reads a key and displays its value:

using System;using Microsoft.Win32; { public static void Main(String[] args) { RegistryKey regKey; Object value; regKey = Registry.LocalMachine; regKey = regKey.OpenSubKey("HARDWAREDESCRIPTIONSystemCentralProcessor "); value = regKey.GetValue("VendorIdentifier"); Console.WriteLine("The central processor of this machine is: {0}.", value); }}

Q: How do I do implement a trace and assert? A: Use a conditional attribute on the method: class Debug { [conditional("TRACE")] public void Trace(string s) { Console.WriteLine(s); } } class MyClass { public static void Main() { Debug.Trace("hello"); } } In this example the call to Debug.Trace() is only made if the preprocessor symbol TRACE is defined at the call site. You can define preprocessor symbols on the command line using the /D switch. The restriction on conditional methods is that they must have void return type. 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.Difference between directcast and ctype. Answer1 [DirectCast requires the run-time type of an object variable to bethe same as the specified type.The run-time performance ofDirectCast is better than that of CType, if the specified type and the run-time typeof the expression are the same. Ctype works fine if there is a valid conversion defined between the expression and the type. ] Answer2 [The difference between the two keywords is that CType succeeds as long as there is a valid conversion defined between the expression and the type, whereas DirectCast requires the run-time type of an object variable to be the same as the specified type. If the specified type and the run-time type of the expression are the same, however, the run-time performance of DirectCast is better than that of CType. ]

An example of a ctype and directcast. In the preceding example, the run-time type of Q is Double. CType succeeds because Double can be converted to Integer, but DirectCast fails because the run-time type of Q is not already Integer ctype(123.34,integer) - should it throw an error? Why or why not? Answer1 [It would work fine. As the runtime type of 123.34 would be double, and Double can be converted to Integer. ] Answer2 [the ctype(123.34,integer) will work fine no errors ] directcast(123.34,integer) - should it throw an error? Why or why not? It would throw an InvalidCast exception as the runtime type of 123.34 (double) doesnt match with Integer. Difference between a sub and a function. Answer1 [A Sub does not return anything whereas a Function returns something. ] Answer2 [-A Sub Procedure is a method will not return a value -A sub procedure will be defined with a Sub keyword Sub ShowName(ByVal myName As String) Console.WriteLine(My name is: & myName) End Sub -A function is a method that will return value(s). -A function will be defined with a Function keywo rd Function FindSum(ByVal num1 As Integer, ByVal num2 As Integer) As Integer Dim sum As Integer = num1 + num2 Return sum End Function] Explain manifest & metadata. Answer1 [Manifest is metadata about assemblies. Metadata is machine-readable information about a resource, or data about data. In .NET, metadata includes type definitions, version information, external assembly references, and other standardized information. ] Answer2 [Manifest: Manifest describes assembly itself. Assembly Name, version number, culture, strong name, list of all files, Type references, and referenced assemblies. Metadata: Metadata describes contents in an assembly classes, interfaces, enums, structs, etc., and their containing namespaces, the name of each type, its visibility/scope, its base class, the nterfaces it implemented, its methods and their scope, and each methods parameters, types prop erties, and so on. ]

Difference between imperative and interrogative code. There are imperative and interrogative functions. Imperative functions are the one which return a value while the interrogative functions do not return a value. Difference between value and reference type. what are value types and reference types? Value type - bool, byte, chat, decimal, double, enum , float, int, long, sbyte, short, strut, uint, ulong, ushort Value types are stored in the Stack Reference type - class, delegate, interface, object, string Reference types are stored in the Heap What are the two kinds of properties. Two types of properties in .Net: Get and Set Explain constructor. Constructor is a method in the class which has the same name as the class (in VB.Net its New()). It initializes the member attributes whenever an instance of the class is created. Describe ways of cleaning up objects. Answer1 [There is a perfect tool provide by .net frameworks calls Garbage collector, where by mean of GC we can clean up the object and reclaim the memory. The namespace used is System.GC ] Answer2 [the run time will maintain a service called as garbage collector. This service will take care of deallocating memory corresponding to objects. it works as a thread with least priority. when application demands for memory the runtime will take care of setting the high priority for the garbage collector, so that it will be called for execution and memory will be released. the programmer can make a call to garbage collector by using GC class in system name space. ] How can you clean up objects holding resources from within the code? Call the dispose method from code for clean up of objects Which controls do not have events? Timer control. What is the maximum size of the textbox? 65536. Which property of the textbox cannot be changed at runtime? Locked Property. Which control cannot be placed in MDI? The controls that do not have events. What is the difference between proc. sent BY VAL and BY SUB? BY VAL: changes will not be reflected back to the variable. By REF: changes will be reflected back to that variable.( same as & symbol in c, c++)