You are on page 1of 74

What is static constructor?

Static constructor is used to initialize static data members as soon as the class is referenced first time, whereas an instance constructor is used to create an instance of that class with keyword. A static constructor does not take access modifiers or have parameters and can't access any non-static data member of a class.

What is the use of Monitor in C#?

It provides a mechanism that synchronizes access to objects.

The Monitor class controls access to objects by granting a lock for an object to a single thread. Object locks provide the ability to restrict access to a block of code, commonly called a critical section. While a thread owns the lock for an object, no other thread can acquire that lock. You can also use Monitor to ensure that no other thread is allowed to access a section of application code being executed by the lock owner, unless the other thread is executing the code using a different locked object.

For more visit

What is lock statement in C#?

Lock ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread attempts to enter a locked code, it will wait, block, until the object is released.

Is overriding of a function possible in the same class?

NOTE: This is objective type question, Please click question title for correct answer.

How to loop through all rows of the DataTable?

You can do this in more than one way but ForEach loop is much better than any other way in terms of cleanliness of the code or performance.

ForEach loop foreach (DataRow row in dTable.Rows)


yourvariable = row["ColumnName"].ToString();


For loop

for (int j = 0; j< dTable.Rows.Count; j++)


yourvariable = dTable.Rows[j]["ColumnName"].ToString()l


What is an Array?

An array is a collection of related instance either value or reference types. Array posses an immutable structure in which the number of dimensions and size of the array are fixed at instantiation.

C# Supports Single, Mult dimensional and Jagged Array.

Single Dimensional Array: it is sometimes called vector array consists of single row.

Multi-Dimensional Array: are rectangular & consists of rows and columns.

Jagged Array: also consists of rows & columns but in irregular shaped (like row 1 has 3 column and row 2 has 5 column)

What is an ArrayList?

ArrayList is a dynamic array. Elements can be added & removed from an arraylist at the runtime. In this elements are not automatically sorted.

What is BitArray?

The BitArray collection is a composite of bit values. It stores 1 or 0 where 1 is true and 0 is false. This collection provides an efficient means of storing and retrieving bit values.

What is HashTable?

A Hashtable is a collection of key-value pairs. Where the collection is sorted by key. It is ideal for messaging components. IDeserializable collback interface. What is SortedList? This is a collection and it is a combination of key/value entries and an ArrayList collection. ISerilizable. What is Queue? This is a collection that abstracts FIFO (First In First Out) data structure. . What is Delegates? A delegate in C# allows you to pass method of one class to objects of other class that can call these methods. It implements IDictionary. What is Stack? This is a collection that abstracts LIFO (Last In First Out) data structure in which initial capacity is 32. The initial capacity is 32 elements. OR A delegate is an object that holds the reference to a method. Entries in this are instance of DictionaryEntry type.

its metadata at run-time. the application details (assemblies). Edited: See the example: http://www. but also the version of the assembly. OR Reflection is the ability to find out information about objects.NET? Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32). What is reflection? Reflection is the ability to find the information about types contained in an assembly at runtime.aspx How is the DLL Hell problem solved in . Are private class-level variables inherited? .com/articles/article132.In C++ it is called function pointer. All classes implement ICollection interface which intern implement IEnumerable interface.dotnetfunda. What is a collection? A collection serves as a container for instances of other classes.

The CopyTo() method copies the elements into another existing array. What are the different ways a method can be overloaded? . Can you prevent your class from being inherited by another class? Yes. but they are not accessible. How can you sort the elements of the array in descending order? By calling Array. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array.CopyTo() and System. they are inherited.Reverse() methods. Although they are not visible or accessible via the class interface.Sort() and then Array.Array. Both perform a shallow copy. What’s the difference between the System.Clone()? The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The keyword “sealed” will prevent the class from being inherited. but prevent the method from being over-ridden? Yes. What class is underneath the SortedList class? A sorted HashTable. resulting in a different. Can you allow a class to be inherited.Yes. A deep copy (which neither of these methods performs) would create a new instance of each element's object. Just leave the class public and make the method sealed. yet identacle object.Array.

} int Age { get.ExecuteReader(CommandBehavior. public int PersonID { get { return m_PersonID. How to declare a property in a class? int m_PersonID = 0.set. different order of parameters. What is the use of CommandBehavior.} . This will make sure that when we are calling reader. } } How to declare a property in an Interface? DateTime DateOfBirth { get. } set { m_PersonID = value. different number of parameters.Close() the associated connection object will also be closed.CloseConnection? We can use pass it with ExecuteReader method of Command object like reader = cmd.Different parameter data types.CloseConnection).set.

How to load assembly from GAC? Lets say you have to load the assembly from GAC on button click event then you should write following method.set. so no implementation required only definition of properties are required. string lastName. protected void btn_Click(object sender. int Insert(string firstName. How to declare methods into an Interface void Calculate(). Implementation of these properties will be written into the class inherting this interface.string FirstName { get.} As this is an Interface. EventArgs e) { . Interface doesn't contain implementation so methods implementation will be written into class inherting this interface. int age).

PublicKeyToken=fbc28d9ca2fc8db5"). Assembly al = Assembly. Culture=neutral.Invoke(null.1.GetType("ClassLibrary1. MethodInfo m = t. Type t = al.AssemblyName asm = new AssemblyName("ClassLibrary1.0. Version=1. .Class1").GetMethod("Method1").Load(asm). str = "reflection .0. null)." + (string)m.

For eg: <object>.We can set a alert message to says that this object is going to dispose.Show(str). What does the term immutable mean? . } For more visit Finalize is used to fire when the object is going to realize the memory.html Difference Between dispose and finalize method? Dispose is a method for realse from the memory for an object.

To Do: Investigate Types of Errors ? Configuration Errors . but as far as compiler cares you’re okay.String is immutable. What’s the difference between System. but they are not accessible.StringBuilder classes? System. so implementation is left entirely up to you.The data value may not be changed.String and System. Are private class-level variables inherited? Yes. but the original immutable data value was discarded and a new data value was created in memory. Note: The variable value may be changed. This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data. they are inherited. What class is underneath the SortedList class? A sorted HashTable What happens if you inherit multiple interfaces and they have conflicting method names? It’s up to you to implement the method inside your own class. Although they are not visible or accessible via the class interface.Text. System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.

How to convert a sentence into Title Case (Capitalize first character of every word)? Use ToTitleCase method.Globalization. Like is a very good website&quot. structures can implement interfaces. System. Classes can have explicit parameter less constructors.CultureInfo. memory will be allocated on the heap and when struct gets initiated it gets memory on the stack. No inheritance for structs.Parser Errors Compilation Errors Run-Time Errors Difference between classes and structures? A struct is a value type and a class is a reference type. But structs dosn't have this. Classes support inheritance. The output will be "Dotnetfunda. and it cannot be the base of a class.dotnetfunda.Com Is A Very Good Website" .ToTitleCase(&quot.CurrentCulture.TextInfo. When we instantiate a class. A struct cannot inherit from another struct or class.).

// sort in ascending order foreach (int i in number) { lblMessage. int[] number = new int[] {6. 7}. } // reverse ie descending order Array.Sort and then use Array.Text += "<hr />".Text += i + " <br />". Array.Reverse(number).Sort(number). .Reverse Eg. 4. lblMessage.How to sort an array into descending order? First sort the array using Array.

FileStream) and you want to show its content. MemoryStream. } .Position != myStream.ReadByte()). myStream.WriteLine("{0:x2}".Length) { Console.Text += i + " <br />". // here theStream is the stream object while (myStream. } How to read entire stream contents? If you have a stream object (any of the stream like StreamReader. write following code.foreach (int i in number) { lblMessage.

IO.WriteAllText(@"c:\MyTextFile. the variable has not changed.IO.txt")). Write a single line of code to create a text file and write contents into it. The procedure changes the variable.File. "MyContents"). however. when the procedure returns.ReadAllText(Server. "shyam".AddRange(arr).MapPath("~/MyTextFile. What is the best way to add items from an Array into ArrayList? Use AddRange method of the ArrayList.Write a single line of code to read the entire content of the text file. What happened? (Choose one. You pass a value-type variable into a procedure as an argument. arrList.) . ArrayList arrList = new ArrayList().File. User following code string strContent = System. Use following code System. "mohan" }. string[] arr = new string[] { "ram".txt".

When should you use the StringBuilder class instead of the String class? NOTE: This is objective type question. Please click question title for correct answer. You must be able to pass the class or structure to a procedure without concern that the procedure will modify it. Please click question title for correct answer. Please click question title for correct answer. You must create the class or structure so that it runs as efficiently as possible. Please click question title for correct answer. Please click question title for correct answer.NOTE: This is objective type question. Please click question title for correct answer. Which of the following should you create? NOTE: This is objective type question. What is the correct order for Catch clauses when handling different exception types? NOTE: This is objective type question. Why should you close and dispose of resources in a Finally block instead of a Catch block? NOTE: This is objective type question. Which of the following is NOT Value type variable? NOTE: This is objective type question. You need to create a simple class or structure that contains only value types. Which of the following statements are false? .

Please click question title for correct answer. Structures inherit ToString from System. and you need to dispose of the generic objects. Please click question title for correct answer. Please click question title for correct answer. If there is no valid conversion between two types. . Which of the following are not examples of built-in generic types? NOTE: This is objective type question.NOTE: This is objective type question. Please click question title for correct answer. How can you do this? NOTE: This is objective type question. Please click question title for correct answer. Why would someone override that method within a structure? NOTE: This is objective type question.Object. Please click question title for correct answer. what should you do when implementing the IConvertible interface? NOTE: This is objective type question. You are creating a generic class. Why should boxing be avoided? NOTE: This is objective type question.

Please click question title for correct answer. Please click question title for correct answer. Which of the following create a FileStream for writing when you want to open an existing file or create a new one if it doesn’t exist? NOTE: This is objective type question. Please click question title for correct answer. which of the following would allow an implicit conversion? NOTE: This is objective type question. Which are NOT acceptable ways to open a file for writing? NOTE: This is objective type question. Which of the following are types of changes that can be detected by the File-SystemWatcher? NOTE: This is objective type question. What types of data can a GZipStream compress? . Which methods of the FileStream class doesn't affect the Position property? NOTE: This is objective type question. How do you not force changes in a StreamWriter to be sent to the stream it is writing to? NOTE: This is objective type question. Please click question title for correct answer.With strict conversions enabled. Please click question title for correct answer. Please click question title for correct answer.

such as compiler instructions and other data about your data. Please click question title for correct answer.NET Reflection. moreover dataset is disconnected and is not aware of the data source. methods. Attributes can be used to identify or use the data at runtime execution using .NOTE: This is objective type question. Please click question title for correct answer. What is the difference between Data Reader & Dataset? Data Reader is connected. . relations and constraints. to the program itself. Dataset is in memory database that can store multiple tables. and classes. What methods can not be used to create a new isolatedStorageFile object? NOTE: This is objective type question. read only forward only record set. Please click question title for correct answer. An IsolatedStorageFileStream object can be used like any other FileStream object? NOTE: This is objective type question. What is Attribute Programming? What are attributes? Where are they used? Attributes are a mechanism for adding metadata. Attributes are inserted into the metadata and are visible through ILDasm and other metadata-reading tools. Is String is Value Type or Reference Type in C#? String is an object (Reference Type).

But it makes no statement about whether you can trust the identity of that publisher. What is garbage collection? . it is also expensive. no fees to pay. This is done using an SDK tool called SN. In addition. The Common Language Runtime. Compilers targeting the . Multiple application domains can exist in a single operating system process. making them a lightweight means of application isolation. the overhead for verifying a strong name is much less than it is for Authenticode. It is common to keep a copy of a common public key in a source database and point build scripts to this key. This ensures that it does not access memory outside the boundaries of the domain. does that require the overhead of signing and managing key pairs? Building a shared assembly does involve working with cryptographic keys. anywhere along the sequence of object activations beginning with the application entry point) are created within the same application domain. Only the public key is strictly needed when the assembly is being built.If I want to build a shared assembly.NET Framework provide command line options (or use custom attributes) for supplying the public key when building the assembly. the assembly must be fully signed with the corresponding private key. Strong name signing does not involve certificates like Authenticode does. and that the assembly loaded on your behalf at run time comes from the same publisher as the one you developed against. strong names do not make any statements about trusting a particular publisher. Before the assembly is shipped. There are no third party organizations involved. All objects created within the same application scope (in other words. While this is effective. on the other hand. What is an application domain? An application domain (often AppDomain) is a virtual process that serves to isolate an application. However. and does not scale to the numbers required for large web servers. enforces application isolation by managing the memory use of code running within the application domain. It is important to note that only type-safe code can be managed in this way (the runtime cannot guarantee isolation when unsafe code is loaded in an application domain).exe (Strong Name). Strong names allow you to ensure that the contents of a given assembly haven't been tampered with. An OS process provides isolation by having a distinct memory address space. and no certificate chains.

like the one used by .aspx What is nested class? A Nested classes are classes within classes. See what is nested class http://www. For more details see http://www.aspx . What is top-level class? A top level class is a class that is not a nested OR A nested class is any class whose declaration occurs within the body of another class or interface. called a "finalizer. compact memory and therefore decrease your program's working set. Which namespace is required to use Generic List? NOTE: This is objective type question.codeproject.NET. It then automatically releases the memory used by that object (as well as calling a clean-up routine.dotnetfunda. Some garbage collectors. Please click question title for correct answer." which is written by the user).Garbage collection is a mechanism that allows the computer to detect when an object can no longer be

NET Framework 2..0.asp. struct.aspx What is extension method in C#? Extension method is a new feature in C# 3. For more detail see http://msdn. This means that if you want to add some methods into the existing String class you can do it quite easily.aspx Which type is inherited by Structs by default? ..80).. see http://weblogs. properties or events * Use extension methods sparingly.0 version. Extension methods allow existing classes to be extended without relying on inheritance or having to change the class's source code.What is partial class? Partial class is a new functionality added in since . interface into multiple source files.overuse can be a bad thing! For more details. It allows to split us to split the definition of once Each source file contains a section of definition. and all parts are combined when the application is Here's a couple of rules to consider when deciding on whether or not to use extension methods: * Extension methods cannot be used to override existing methods * An extension method with the same name and signature as an instance method will not be called * The concept of extension methods cannot be applied to fields.

Please click question title for correct answer. What is the default modifier for the class member? NOTE: This is objective type question.0. Which type is inherited by Class by default? NOTE: This is objective type question. Please click question title for correct answer.NOTE: This is objective type question. Please click question title for correct answer.Object. . eg. What is the default modifier for class in C#? NOTE: This is objective type question. by default a class inherit System. What is the use of var keyword in C#? This is the new feature in C# 3. This enable us to declare a variable whose type is implicitly inferred from the expression used to initialize the variable. Please click question title for correct answer. By default which class is inherited by a class in C#? If no class is inhertited.

What is extension method in C#? . They can't be used as a member of the class. Note that anonymous types are just a placeholder. There are few limitation of the var type of variables. _Gender. #. This is especially useful when we want to receive data from other object or iterate through a collection and set values and do not want to create a class just to hold the data. Gender. Because the initialization value (10) of the variable age is integer type of age will be treated as integer type of variable. They can't be initialized as null. #. This enable use to create a type/class on-the-fly at compile time. They need to be declared and initialized in the same statement. They are: #.var age = 10. What is anonymous type in C#? This is a new feature in C# 3. Gender = "Male". and Active as public property and its backing field like _Name. In this case a new type will be created on the fly that will have Name. _Active.0. we can't customize its behavior or add methods inside it. Active = true }. For example var emp = new { Name = "Sheo".

In this case as the format of the email id in myEmail variable is correct so IsValidEmailAddress will be true.IsValidEmail(). . For". public static bool IsValidEmail(this string input) { Regex regEx = new Regex(@"\w+([-+. we can use above extension method like this. } Notice the parameter passed to above method. we can add an extension method like this. Now.']\w+)*@\w+([-.IsMatch(input). Here "this" indicates the string class.\w+([-. if we want to validate an Email address using the static method of the string class (built-in) class. string myEmail = "me@me.]\w+)*\. bool IsValidEmailAddress = myEmail. This method allows us to add a new static method to the existing classes. return regEx.]\w+)*").0.This is a new feature in C# 3.

. Differrence between Array. 2. Clone() method makes a clone of the original array. this adds elements to an already existing array. The constructor provides a way to set default values for data or perform other necessary functions before the object available for use. It returns an exact length array. In visual basic a constructor is always Sub new (). 3. CopyTo() copies the elements from the original array to the destination array starting at the specified destination array index. Constructor are use to initialize class and structure data before use. The Constructor is the first method that is run when an instance of a type is created.Clone() Both CopyTo() and Clone() make shallow copy (data is copied) and used for Single Dimension arrays. You can’t control when a destructor is called.CopyTo() and Array.Constructor and Destructor Constructor: ----------------- 1. Destructor: --------------Destructors are called just before an object is destroyed and can be used to run clean-up code. Note that. Constructor never returns a value and can be overridden to provide custom initialization functionality.

Text.staticmember 3)'this ' keyword cannot be used inside a static memberfunction 4)Nonstatic members cannot be used inside a static memberfunction What’s the advantage of using System.StringBuilder over System. The difference arise on mentioning the size of the array.NET. Below is the code which would throw some light on your understanding. variables has to be declared earlier.In VB. If value type is used for CopyTo/Clone any change in the values made on them will not get reflected on the original whereas on reference type the change gets reflected. Syntax: classname. rather the array size gets altered automatically on cloning. 2)Static members can be called with the help of Classname. While declaring the variable that is used for Clone method we need not mention the array size.String? . before using Clone or CopyTo methods to store the values. what is Static? Static: 1)A Static memberdata or a memberfunction can be called without the help of an object. Eventhough the array size is small. The cloned array size get created equal to the size of the source array. While declaring the varaiable that is used for CopyTo method. it should have the size equal to or more than that of the original array. it won't show any error.

The program proceeds without any interruption if the condition is true. assert takes in a Boolean condition as a parameter. Strings are immutable. so each time a string is changed. When at least one of the methods in the class is abstract. Each assigned handler (method) is called. When do you absolutely have to declare a class as abstract? 1. When the class itself is inherited from an abstract class. and shows the error dialog if the condition is false. What’s a multicast delegate? A delegate that has multiple handlers assigned to it. 2. What is a satellite assembly? . a new instance in memory is created. What does assert() method do? In debug compilation. but not all base abstract methods have been overridden.StringBuilder is more efficient in cases where there is a large amount of string manipulation. What’s a delegate? A delegate object encapsulates a reference to a method.

and want to distribute the core application separately from the localized modules. internally the code is generated like this SqlConnection conn = new SqlConnection() try . IDisposable interface has one public method called Dispose that is used to dispose off the object.NET. Using (SqlConnection conn = new SqlConnection()) { } When we use above block.but it supports static method How and why to use Using statement in C#? Using statement is used to work with an object in C# that inherits IDisposable interface. the localized assemblies that modify the core application are called satellite assemblies. the using statement takes care of it. For eg.because c# doesnot support static block. can we declare a block as static in c#? NO.When you write a multilingual or multi-cultural application in . we don't need to explicitly dispose the object in the code. When we use Using statement.

cs file you can use . eg. to create the executable of the .com/KB/cs/tinguusingstatement. For more details read http://www.{ } finally { // calls the dispose method of the conn object } Using statement make the code more readable and compact.aspx What is the name of C# compiler? The name of C# compiler is CSC.codeproject.

com/en-us/library/78f4aasd. This concept has been better explained in following article the pool manager will take the request and it will be served by allocating an object from the .cs This will create File.aspx What is object pooling? Object Pooling is something that tries to keep a pool of objects in memory to be re-used later and hence it will reduce the load of object creation to a great extent.aspx How to create a strong name? To create a strong name key use following code C:\>sn -k s.c-sharpcorner. For more details visit: http://msdn.chn/109042007094154AM/1.exe File. Object Pool is nothing but a container of objects that are ready for use. Whenever there is a request for a new object.

Strong name key is used to specify the strong name used to deploy any application in the GAC (Global Assembly Catch) in the system. What is Global Assembly Cache? Abbreviated as GAC. the C# complier will group all the partial classes together and treat them as a single class.webopedia. For more details visit http://www. C# Public partial class Employee { public void DoWork() . When the application is complied. you can split the definition into multiple classes by using the partial keyword.htm What is Partial Class? Partial class Instead of defining an entire class. Each computer where the common language runtime (CLR) is installed has a global assembly cache. Also you can separate your application business logic from the designer-generated code. The global assembly cache stores the assemblies specifically designated to be shared by several applications on the computer. the Global Assembly Cache is a machine-wide store used to hold assemblies that are intended to be shared by several applications on the Programmers can work on different parts of a class without needing to share the same physical file. There are a couple of good reasons to use partial classes.

which are symbols that specify which operations to perform in an expression.{} } Public partial class Employee { public void GoToLunch() {} } What is operators in C# and how many types of operators are there in c#? C# has a large set of operators. Arithmetic +-*/% .

Logical (boolean and bitwise) & | ^ ! ~ && || true false

String concatenation +

Increment, decrement ++ --

Shift << >>

Relational == != < > <= >=

Assignment = += -= *= /= %= &= |= ^= <<= >>=

Member access .

Indexing []



Conditional ?:

Delegate concatenation and removal +-

Object creation new

Type information as is sizeof typeof

Overflow exception control checked unchecked

Indirection and Address * -> [] &

For more details visit

What is operator overloading in C#?

Operator overloading is a concept that enables us to redefine (do a special job) the existing operators so that they can be used on user defined types like classes and structs.

For more information visit: What are Sealed Classes in C#?

The sealed modifier is used to prevent derivation from a class. A compile-time error occurs if a sealed class is specified as the base class of another class. (A sealed class cannot also be an abstract class)

What are the access-specifiers available in c#?

Private, Protected, Public, Internal, Protected Internal.

How to explicitly implement the interface method?

To explicitly implement interface we need to prefix the method name with the name of the interface following by .(dot).

string IInterface1.HelloNet()


return "Interface 1 : Hello NET";


Assuming that HelloNet method is in IInterface1 as well as another interface that is inherited in the class.

How to write a method in a class and build as . using System. 3. using System. using System.How to declare a method in an Interface? To declare method in an interface. 2. void ProcessMyData(int id). Right click your solution and select New Project.Collections. Select Visual C# as Project type and Class Library as Templates (give proper name and location path) and click OK.dll you can following below steps 1. you just need to write the definition of the method like below.Generic.Linq. . you can add as many class you want. There is no need of writing the modifier as by default all methods in the interface is public.dll To generate a . Write some code in the class like below. string GetMyName(int id).

using System. Right click the Class Library project and select build.Text. . } } 4. namespace ClassLibrary1 { public class Class1 { public string GetMyName(string myName) { return myName.using System.IO.

dll you have just generated. Select browse tab from the dialogue box and choose the . you can right click your project and select Add References. What is UDP and how does it work? The User Datagram Protocol (UDP ) provides an unreliable datagram-oriented . To refer this . This will pass the numeric by reference. string myName = c. Your . 7. Instantiate the class and use its method like below Class1 c = new Class(). Thanks :) How do I call a member method and pass a primitive type (Value Type) by reference? public bool GetValue( ref int returnValue ).dll should be ready in the bin folder of the project location (either in the debug or release folder) depends on which mode your project is. 8. 6.dll.5. you can use the namespace you had used in the class library (in above case ClassLibrary1) like "using ClassLibrary1. Now to use the method of the class library in any code behind page or another class library.GetMyName("Poster")." 9.You can modify the value of returnValue within the body of GetValue and it will persist when the method call returns.

How can I programmatically list available queues? The GetPublicQueuesByLabel . ReadOnly: you can’t change its value. Please click question title for correct answer. the GetPublicQueues method has a MessageQueueCriteria parameter in which you can specify combinations of search criteria. Please click question title for correct answer. It is connection-less.The delivery and order of datagrams are not guaranteed.To specify more exactly the type of queue you are looking for. a UDP application does not have to connect explicitly to another. Which of the following is Mutable? NOTE: This is objective type question. GetPublicQueuesByCategory . Datagrams are simply sent or received. and GetPublicQueuesByMachine methods of the MessageQueue class provide access to queues on a network. Which is the Best one for using String concatenation? NOTE: This is objective type question. .protocol on top of IP. Difference between Static and ReadOnly? Static: A variable that retains the same data throughout the execution of a program. that is.

Combined with metadata and the common type system. Difference Between String and StringBuilder String Class .NET programming language (C#. Please click question title for correct answer. then run on the host machine. String str2=str1. MSIL allows for true cross.since our source code in automatically converted to MSIL. NOTE: This is objective type question. MSIL is similar to Java Byte code. It is not interpreted. The MSIL code is then send to the CLR (Common Language Runtime) that converts the code to machine language. storing. MSIL is converted to machine code. Console.HashTable Class is present inside which of the following NameSpace? NOTE: This is objective type question. Please click question title for correct answer.NET. which is. initializing. MSIL is the CPU-independent instruction set into which . It contains instructions for loading. As a programmer one need not worry about the syntax of MSIL . Please click question title for correct answer. In C# int Refer to? NOTE: This is objective type question. instead it compiles into an intermediate code called Microsoft Intermediate Language (MSIL). What is Microsoft Intermediate Language (MSIL)? A . VB. What will be the output for the following: String str1="Hello".) does not compile into executable code.language integration Prior to execution. str1=str1+"C#".NET Framework programs are compiled. J# etc. and calling methods on objects.WriteLine(str2).

microsoft.NET Framework common language runtime.exe to debug managed code. its length and content cannot be modified. Please click question title for correct answer.exe) provides debugging services with a graphical interface to help application developers find and fix bugs in programs that target the common language runtime. The Microsoft CLR Debugger (DbgCLR. Click for more details http://msdn. . Developers can examine the code to learn how to use the debugging services. the documentation refers mostly to the Visual Studio Debugger. The CLR Debugger.aspx DbgCLR – graphic debugger. Currently. To use CorDbg. you must compile the original C# file using the /debug switch. there is no support for debugging unmanaged code. As a is based on work being done for the Microsoft Visual Studio 2005 Debugger. Faster Which of the following class does not belong to Collection namespace ? NOTE: This is objective type question.Once the string object is created.NET Framework SDK? CorDBG – command-line debugger The Runtime Debugger helps tools vendors and application developers find and fix bugs in programs that target the . Slower StringBuilder Even after object is created. and the accompanying documentation. you can only use Cordbg.80). This tool uses the runtime Debug API to provide debugging services. it can be able to modify length and content. What debugging tools come with the .

rather than the CLR Debugger. How to: Use the Registers Window. Here are some of the main differences between the CLR Debugger and the Visual Studio Debugger as described in the documentation: * The CLR Debugger does not support the debugging of Win32 native code applications. * The Disassembly window is implemented in the CLR Debugger but shows the disassembly code that would be generated for the application if it were compiled as Win32 native code rather than common language runtime are not supported. * The CLR Debugger does not support the Autos window feature. such as displaying or changing a register value. * Remote debugging is not implemented in the CLR Debugger. the information is applicable to both debuggers. Only applications written and compiled for the common language runtime can be debugged with the CLR Debugger. Other operations that involve registers or pseudoregisters. In most cases. However. Click for more details http://msdn. How to: Use the Disassembly Window. but no register information appears in the window.aspx What are three test cases you should do while unit testing? . For more information see. you will find sections of the documentation describing some features that are not implemented in the CLR Debugger (see the next paragraph).80). * The CLR Debugger does not support F1 help. * The Registers window is implemented in the CLR Debugger. You can simply ignore these features and sections. For more information

A try having more than one catch block will fire the first relevant catch block after that cursor will be moved to the finally block (if exists) leaving all remaining catch blocks. try { int i=10. } } catch(Exception ex) { throw ex. j=i/j. . j=j-i. Thanks In this Sample Code which catch block will be executed? try { int j=10. A try block having 4 catch block will fire all catch block or not? No. } catch(Exception ex) { throw ex.Positive test cases This is done with correct data to check for correct output) Negative test cases This is done with broken or missing data to check for proper handling Exception test cases This is done with exceptions (giving unexpected data or behavior) and check for the exception caught properly or not. So in all cases only one catch block will fire. } NOTE: This is objective type question. Please click question title for correct answer. Please click question title for correct answer. Which keyword is used to prevent one class from being inherited by another class in C# NOTE: This is objective type question.

int j = 1. How to Find Number of Days for provided date range? Code extract : . What Will be the output of the following Code? int i = 1. Please click question title for correct answer. The exceptions which cant be handled in the defined catch block are thrown to its caller.Can you store multiple datatypes in an Array? NOTE: This is objective type question. Which namespace is used to work with RegularExpression in C#? NOTE: This is objective type question. Please click question title for correct answer. NOTE: This is objective type question. Can we throw exception from catch block ? Yes. Response. Please click question title for correct answer. An array is fixed length type that can store group of objects. NOTE: This is objective type question.Write(i. i = i++.ToString() + ":" + j. j = ++j.ToString()). Please click question title for correct answer.

Subtract(Convert. The Subtract method does not take start date into consideration. Response.Write("Number of Days : " + DayDifference. to get the exact number of days for the date range we need to add one more day to the result.Days+1). Hence. Can you do this with CompareValidator? Yes. To find the difference of the days.ToDateTime("2009-1-7"). here we have used Subtract method.TimeSpan DayDifference = Convert. With the validator control.ToDateTime("2009-1-1")). You have to make user to enter just integer values with TextBox. you need to set type attribute to the desired datatype which in this case is “Integer” and Operator to DataTypeCheck. <asp:CompareValidator ID="CompareValidator1" ControlToValidate="TextBox1" Type="Integer" Operator="DataTypeCheck" runat="server" ErrorMessage="CompareValidator"></asp:CompareValidator> How can you cache Multiple Versions of a Page? Using output cache you can cache multiple versions of the page. .

For an example: To turn off caching. With @ OutputCache directive four parameters of VaryByParam .SetExpires(DateTime. request's HTTP header respectively.Cache.SetCacheability(HttpCacheability.@ OutputCache directive at design time declaratively for Declarative Approach OR . VaryByHeader.Cache.Response.… . Declarative Approach: <%@ OutputCache Location="None" VaryByParam="None" %> Programmatic Approach: Response.AddSeconds(60)).Now.We can either use. VaryByCustom allows user to cache page depending on query string.Cacheclass at runtime for Programmatic Approach. .NoCache). VaryByControl. To cache the output for each HTTP request that arrives with a different ID: Declarative Approach: <%@ OutputCache duration="60" varybyparam=" ID" %> Programmatic Approach: Response. request's HTTP header. control value.

VaryByParams["ID"] = true.NoAbsoluteExpiration. null. Is it possible to notify application when item is removed from cache ? Yes.Response. Cache. You can use CacheItemRemovedCallback delegate defining signature for event handler to call when item is removed from cache.Insert( "CacheItem1". Response.Default.Cache. CacheItemPriority.Cache. //insert cache item "".Cache.SetCacheability(HttpCacheability. 15). . new TimeSpan(0. 0.Public). For an example: HttpRuntime.

Now.Empty.0? No. var keyword is used to declare implicitly typed local variable. private static string RemovedAt = string.ToString(). . //define method which needs to be called when item is removed from cache the method will be like. public static void RemovalMethod(String key. object value. //method is declared static so that it can be available when cache item is deleted CacheItemRemovedReason removedReason) { RemovedAt = "Cache Item Removed at: " + DateTime. but the compiler determines the type. //Shows the time when cache item was removed } Can we declare an array variable with var keyword in C# 3. An implicitly typed local variable is strongly typed just as if you had declared the type CacheItemRemovedCallback(RemovalMethod)).

So you can declare a local variable of any type using var keyword but you can't declare an array of variable using var keyword. } Wrong var[] str = { "ram". Correct string[] str = { "ram". "sham" }.Write(s + "<br />"). foreach (var s in str) { . "sham" }. foreach (var s in str) { Response.

Response.LinkedList<T>. For more info on var keyword see http://msdn. Please click question title for correct answer.Write(s + "<br />").Stack<T>. Please click question title for correct answer.Queue<T>. } This will throw "CS0246: The type or namespace name 'var' could not be found (are you missing a using directive or an assembly reference?) " error. Stack is collection where elements are processed in NOTE: This is objective type question.aspx Thanks Give Some Examples of Generic Classes? List<T>.microsoft.HashSet<T> A Queue is a collection where elements are processed in NOTE: This is objective type question. The Items that is put in the Queue is Reads ? .com/en-us/library/bb383973.

Which method is used to return an item from the Top of the Stack? NOTE: This is objective type question. Please click question title for correct answer. Please click question title for correct answer. Which method is used to reads and removes an item from the head of the Queue. .NOTE: This is objective type question. Please click question title for correct answer. generics is not supported for the classes which deos not inherits collect class. Please click question title for correct answer. Whcih method is used to add an Item on stack? NOTE: This is objective type question. Can we define generics for any class? No. NOTE: This is objective type question. Which method is used to add an Item to the end of the Queue? NOTE: This is objective type question. What is the difference between Parse and TryParse method? Parse method is used to parse any value to specified data type. Please click question title for correct answer.

.. **declare variable iResult of Int32. This will work fine bt what if when you are aware about the value of string variable test. Result = Int32. . In that case if u try to use above method. and returns the converted value through an out parameter.For example string test = "42".TryParse(test.. TryParse is a good method if the string you are converting to an interger is not always numeric. int32 Result.NET will throw an exception as you are trying to convert string data to integer. if(!Int32..Parse(test). if test="abc".out iResult)) { //do something } The TryParse method returns a boolean to denote whether the conversion has been successfull or not.

StringBuilder sb2 = new StringBuilder(“Mahesh”). String s2 = “Mahesh”. i == k > True i.Equals(b) and a == b? For value types : “==” and Equals() works same way : Compare two objects by VALUE Example: int i = 5.Equals(k) > True For reference types : both works differently : “==” compares reference – returns true if and only if both references point to the SAME object while "Equals" method compares object by VALUE and it will return true if the references refers object which are equivalent Example: StringBuilder sb1 = new StringBuilder(“Mahesh”). int k= 5.Equals(sb2) > True But now look at following issue: String s1 = “Mahesh”. s1 == s2 > True s1.What is the difference between a.Equals(s2) > True . sb1 == sb2 > False sb1. In above case the results will be.

byte b = 0. By declaring below variable you are assigning default values to second and third parameter of 2 and 3 respectively (param2 and param3). Recommendation : For value types: use “==” For reference types: use Equals method.) Now another interesting case: int i = 0. int param3 = 3). optionalParam(1). it will behave like Value Types in this case. public void optionalParam(int Param1. it means Equals method compare not only value but it compares TYPE also in Value Types.2.Equals(b) > False So. //which will be equivalent to optionalParam(1.String is actually reference type : its a sequence of “Char” and its also immutable but as you saw above. What is optional and named parameter in C#4. Exceptions are always there . int param2 = 2. After this you can write.3). . i == b > True i.0? Optional parameter allows omitting arguments to function while named parameters allow passing arguments by parameter name.

2.. What is obsolete method? Obsolete means old or no longer in use. //which will be equivalent to optionalParam(1. But. Can you have different access modifiers on the get/set methods of a property in C#? No. . We can define a method as obsolete using Obsolete keyword/attribute.10). The access specifier has to be same for get and set. it's not possible. [Obsolete] public int Fun1() { //Code goes here.Sometimes. you may need to not to pass param2. named parameter comes to the picture. param3:10). You can specify arguments like.3) is not valid statement with C#. optionalParam(1. optionalParam(1. At this point.

it will automatically generate current.} or [Obsolete("Any user define message")] public int Fun1() { //Code goes here.. What first action compiler will take on detection of iterator ? As soon as compiler will detect iterator. . } One thing to note here is O is always capital in Obsolete. MoveNext and Disposemethods of the IEnumerator or IEnumerator(T) type.

Please click question title for correct answer. First is .With yield break statement. Checked keyword is used to check the overflow arithmetic checking. we can’t place yield keyword in the catch block if try contains more than one catch blocks. control gets … NOTE: This is objective type question. To indicate that all operations will be performed runtime. Second is .0. . While using yield keyword. mainly two restrictions are observed. What is dynamic keyword ? Its newly introduced keyword of C#4. we can’t use yield in finally. What will happen if you declare a variable named "checked" with any data type? Compiler will throw an error as checked is a keyword in C# So It cannot be used as variable name. Restrictions of yield in try-catch. What are anonymous methods? Anonymous methods are another way to declare delegates with inline code except named methods.

//returns b= 25 } How can you make your machine shutdown from your program? . Example:- unsafe { int a.What is difference between var and Dynamic ? Var word was introduced with C#3.b). b = &a. Use of pointer sometime crashes the application. Console. But C# supports pointer.5(specifically for LINQ) while dynamic is introduced in C#4. But pointer does not come under garbage collection.0. All the exceptions related to dynamic type variables can only be caught at runtime. So if we want to use pointer in C# the pointer must be present in the body of unsafe declaration. variables declared with var keyword will get compiled and you can have all its related methods by intellisense while variables declared with dynamic keyword will never get compiled. The use of pointer in C# is defined as a unsafe code. a = 25. so there is no need of pointer.WriteLine("b= {0}". that means we can use pointer in C#. *b. What is the use of unsafe keyword in C#? In C# the value can be directly referenced to a variable.

Type testType = d. I need to restrict a class by creating only one object throughout the application. How can I achieve this? We can declare the constructor of the class as either protected or as private How do we retrieve day.Process.Month and Year as follows int day = dobDate.i nt year = dobDate. if used. "-s -f -t 0").Month. . int month = dobDate.NullReferenceException" type.GetType(). int? d = 1.Year. month and year from the datetime value in C#? Using the methods Day.Day. will result… NOTE: This is objective type question. So it's length will be null and it will throw a run time exception of "System.Start("shutdown". What will be the length of string type variable which is just declared but not assigned any value? As variable is not initialized and it is of reference type. Please click question title for correct answer.

Which keyword in C# is used to temporarily fix a variable so that its address may be found? fixed keyword What is the use of stackalloc keyword in C#? In an unsafe context it is used to allocate C# array directly on the stack.C# delegate keyword is derived form which namespace? C# delegate keyword is derived form System.MulticastDelegate.Delegate types. #endregion :. #else . Which operators in C# provides automatic detection of arithmetic overflow and underflow conditions? .These are used to conditionally skip sections of source code. What are the different C# preprocessor directives? #region .Used to mark sections of code that can be collapsed. What is the use of GetInvocationList() in C# delegates? GetInvocationList() returns an array of System. #define . #elif . #undef :-Used to define and undefine conditional compilation symbols. #endif :. each representing a particular method that may be invoked. #if .

What is the CIL representation of implicit and explicit keywords in C#? The CIL representation is op_Implicit and op_Explicit respectively. What are the different Iteration Constructs in C#? for loop foreach/in loop while loop do/while loop What are the different method parameter modifiers in C#? out ref params What do you mean by properties in C#? Property acts as a cross link between the field and the method . Actually it behaves as a field. . We can retrieve and store data from the field using property. What is the use of ?? operator in C#? This operator allows you to assign a value to a nullable type if the retrieved value is in fact null.'checked' and 'unchecked' keywords provide automatic detection of arithmetic overflow and underflow conditions.

Square.When there is only get accessor it is called as ReadOnly Property. What is the use of param keyword in C#? In C# param parameter allows us to create a method that may be sent to a set of identically typed arguments as a single logical parameter. WriteOnly Property :. Which enumeration defines different PenCap in C#? LineCap enumeration which defines different pen cap styles as follows.The compiler automatically translates the field like property into a call like special method called as 'accessor" . In property there are two accessor and that are used to save value and retrieve value from the field. ReadOnly Property :. NoAncher. SquareAnchor. Round. The two properties are 'get' and 'set'. . public enum LineCap { Flat. Triangle. The get property is used to retrieve a value from the field and the set property is used to assign a value to a field . Depending on there use properties are categorised into three types.When both get and set properties are present it is called as ReadWrite Property. it is called as WriteOnly Property. ReadWrite Property :.When there is only set accessor. Which class defines different events for controls in C#? The "Control" class defines a number of events that are common to many controls.

RoundAnchor. DiamondAnchor. Invoke() BeginInvoke() and EndInvoke(). ArrowAnchor.NET delegate results in a sealed class with three compiler generated methods whose parameters and return values are dependent on the delegate declaration.Threading. For such situations we can use the System. The methods are.Timer type in conjunction with a related delegate named TimerCallback. AnchorMask. What are the different compiler generated methods when a . Custom } When TimerCallback delegate is used? Many application have the need to call a specific method during regular intervals. I would like to check a variable as assigned or not.NET delegate is compiled? Compilation of a . How can you check a nullable variable is assigned? . How can we do that? Declare the variable as Nullable what is the syntax of a nullable variable? Nullable myval=null.

using hasvalue method Tell me one reason for dotnet doesn't have multiple inheritance To avoid ambiguity and deadlocks I would like to find all the directories of a folder How should I achieve this? By Directory.MoveNext()) { . Below is the sample to do that string str = "my name".GetEnumerator(). CharEnumerator chs = str. while(chs.GetDirectories method What is CharEnumerator in C#? CharEnumerator is an object in C# that can be used to enumerate through all the characters of a string.

Write(chs. will it execute if there is an exception in try block. the code in finally block will execute. Which methods are used to execute javascript code from code behind file? RegisterStartupScript and RegisterClientScriptBlock What is the main difference between RegisterStartUpScript and RegisterClientScriptBlock? RegisterStartUpScript Add the javascript code at the end of the page before the closing of form tag. Yes. S it should be called before the creation of any object. So Main() is declared as static. } Moderator: please do not move this to Code section.Response. If i will write a piece of code in finaly block. By using static the Main() can now be called directly through the class name and there is no need to create the object to call it.Current). while RegisterClientScriptBlock place the code at th top of the page. this is a typical interview question that was asked :) Why 'static' keyword is used before Main()? Program execution starts from Main(). What is the page size in SQL Server? .

Redirect ? No. How we can gt the values of control on the previous page in case od server. what is the class used for dealing with graphics objects System.Graphics is the class used for dealing with graphics objects Write a way to read an image from a path to a bitmap object We can directly read an image file and load it into a Bitmap object as below.PreviousPage to get the value of controls of the previous page in case of response.PreviousPage.FindControl() method.FromFile(strPath).redirect. we can't use PreviousPage to find the control on previous page with response..> 8192 you can check this with the query : SELECT low FROM master.Drawing. . Bitmap myBmpObj = Bitmap.transfer method? Using Page.spt_values WHERE number = 1 AND type = 'E' Can we use Page.8 KB -.

Bitmap loBMP = new Bitmap(strPath). . In C#. a derived class can’t be more accessible than it’s base class. Can we inherit a private class into the public class? No. Code as given below.We can also set Image path during the Initilization of Bitmap Object. Please click question title for correct answer. Modified By: Moderator3 Name any two "Permission Classes" generally used while working with CAS ? 1) FileIOPermission 2) UIPermission 3) SecurityPermission Does Abstract classes contain Constructor? NOTE: This is objective type question. So always the base class should be more or equal accessible than a derived class. It means that you can't inherit a private class into a public class.

// Following will throw compilation error private class BaseClass { } public class DerivedClass : BaseClass { } // Following will compile without an error public class BaseClass { } public class DerivedClass : BaseClass { .

} Hope this helps Can we declare a class as Protected? http://msdn. Abstract Internal Public Sealed Static Extern (The extern modifier is used to declare a method that is implemented externally. A class can be declared with only following access modifiers.80).microsoft. it is forward only collection. IEnumerable<T> doesn't move between items.aspx) Thanks What is the difference between IQueryable<T> and IEnumerable<T> interface? IEnumerable<T> IEnumerable<T> is best suitable for working with in-memory collection. . a class can not be declared as Protected.

like a database or web service. 5. if you need to do any manipulation with the collection like Dataset and other data sources. Override keyword is used provided the method signature of the derived class is same as base class. Virtual method can not be declared as Static 3. if any Some facts about Virtual methods. Please let me know your feedback. Virtual keyword is only used in base and derived class scenario where you want your method overridable in the derived class. use IQueryable<T>. Virtual keyword is used to declare a method inside the base class that can be overridden. So when you have to simply iterate through the in-memory collection. IQueryable<T> is a very powerful feature that enables a variety of interesting deferred execution scenarios (like paging and composition based queries). Virtual method can not be declared as Private 2. Enjoy virtual keyword :) . 4. In order to override the virtual method of the base class. use IEnumerable<T>. 6.IQueryable<T> IQueryable<T> best suits for remote data source. A Virtual method must contain the method body otherwise compiler shall throw error. even the access modifier should be same. Virtual method may or may not be overridden. Following conditions are applied to a virtual method 1.

Out variables are not require to initialize. For example you can't called a function that is designed to call Integer with a string or decimal. the initialized value will not be passed.Method Overriding .Explain About ref and out parameters? ref parameter: Ref is keyword. only reference will be passed. Which must be used along with actual and formal arguments. Example for Compile time Polymorphism and Example for Run time Polymorphism? Example of Compile Time Polymorphism . it must be used along with actual and formal arguments.Method Overloading Example of Run Time Polymorphism . Why C# is called Strongly Typed Language? C# is called Strongly Typed Language becausen its type rules are very strict. Out is a Keyword. If you want to do so then you will have to explicitly convert them to integer. ref variables must be initialized before passing to a function out parameter: It is very similar to call by Reference.

myClassO<int> i = new myClassO<int>(20). // Correct .What is Closed constructed type and Open constructed type? Closed constructed type and open constructed type is term that is used while instantiated an object. For exmaple class myClassO<T> { } Class MyClassC<int> { } In above code class myClassO is the open constructed type as we can pass any type of parameter while instantiating the myClassO object.

myClassC is the closed constructed type as I have specified the type of argument to be passed in the myClassC instantiation.myClassO<string> i = new myClassO<strubg>('my string"). // InCorrect . // Correct myClassC<string> i = new myClassC<strubg>('my string"). myClassC<int> i = new myClassC<int>(20). // Correct You can notice that I can pass either integer or string in the myClassO insntiation as this is the generic class.