Anda di halaman 1dari 42

Page |1

1. What are the advantages of using .NET frame work? The following are the advantages of.NET Framework: Provides Consistent Programming Model Has Language Independence No versioning Problem - Easy Application Deployment and Maintenance Improved Security Support for Web Services Dynamic Web facilities Full fledged Visual Studio.NET 2. Explain different layers of .NET frame work.

Sitting on top of common language runtime is a very large class library which provides all the different platforms, like ADO.NET to access databases or ASP.NET to write Internet-enabled software. These reside in Framework Base Class Library. Sitting on top of all, is ultimately some programming languages. These are the different layers of .NET framework. 3. Explain architecture of .NET frame work. / Draw the architecture of .NET frame work and explain its components The important components of .NET Framework are: Common Language Runtime:- manages the execution of code and provides essential services Assemblies:- consists of IL code, metadata that describes what is in the assembly, and any other files or information that the application needs to run, such as graphics and sound files. Application Domains:- provide a secure and versatile unit of processing that the CLR can use to provide isolation between applications Common Type System:- defines how types are declared, used, and managed in the runtime Metadata and Self-Describing Components:- it is binary information describing the program. When we compile our code into a PE file, metadata is inserted into one portion of the PE file, while the code is converted to IL and inserted into another portion of the PE file. Every type, member which are defined or referenced in a module is described within metadata Common Language Specifications:- define a subset of the CTS i.e., all the rules that apply to the CTS apply to the CLS .NET Framework Class Library:- set of managed classes that provide access to system services. File handling, sockets, database access, remoting, and XML are some of the services available in the Base Class Library

Page |2

4. What is .NET frame work? The .NET Framework is a software framework that runs primarily on Microsoft Windows. It includes a large library and supports several programming languages which allow language interoperability. Programs written for the .NET Framework execute in a software environment, known as the Common Language Runtime (CLR), an application virtual machine that provides important services such as security, memory management, and exception handling. The class library and the CLR together constitute the .NET Framework. 5. What do you mean by backward compatibility in .NET? Explain. Backward compatibility means that an application developed for a particular version of a platform will run on later versions of that platform. The .NET Framework tries to maximize backward compatibility. Source code written for one version of the .NET Framework should compile on later versions of the .NET Framework, and binaries that run on one version of the .NET Framework should behave identically on later versions of the .NET Framework. 6. Explain the compilation of .NET programming languages.

Given above is the process of compilation of .NET programming languages.

Page |3
7. How the windows programming is different from .Net programming? In Windows Programming the application programs call windows API function directly. The applications run in the windows environment i.e. operating system itself. These types of applications are called unmanaged or unsafe applications. In .NET Programming the application programs call .Net Base Class library functions which will communicate with operating system. The applications run in .Net Runtime environment. These types of applications are called as managed or safe applications. The .Net Runtime starts code execution, manages threads, provides services, manages memory etc. 8. Explain remoting architecture. / What is .NET remoting? The .NET remoting infrastructure is an abstract approach to interprocess communication. Much of the system functions without drawing attention to itself. It is able to enable communication between objects in different application domains or processes using different transportation protocols, serialization formats, object lifetime schemes, and modes of object creation. In addition, remoting makes it possible to intervene in almost any stage of the communication process, for any reason. 9. How is .NET remoting different from web services and DCOM? .NET Remoting versus Distributed COM (DCOM) Distributed Component Object Model, or simply DCOM works well and the performance is adequate when applications exist on computers of similar type on the same network. However, DCOM has its drawbacks it relies on a proprietary binary protocol that not all object models support. It also wants to communicate over a range of ports that are typically blocked by firewalls. .NET Remoting eliminates the difficulties of DCOM by supporting different transport protocol formats and communication protocols. This allows .NET Remoting to be adaptable to the network environment in which it is being used. .NET Remoting versus Web Services ASP.NET based Web services can only be accessed over HTTP. Whereas the .NET Remoting can be used across any protocol. Web services work in a stateless environment where each request results in a new object created to service the request. .NET Remoting supports state management options and can identify multiple calls from the same client. Web services serialize objects through XML contained in the SOAP messages and can thus only handle items that can be fully expressed in XML. .NET Remoting relies on the existence of the metadata within assemblies that contain information about data types. This limited metadata information is passed about an object, when it is passed by reference. 10. Define DCOM. Distributed Component Object Model (DCOM) is a proprietary Microsoft technology for communication among software components distributed across networked computers. DCOM, extends Microsoft's COM, and provides the communication substrate under Microsoft's COM+ application server infrastructure. In terms of the extensions it added to COM, DCOM had to solve the problems of: Marshalling Distributed garbage collection Aggregating hundreds or potentially tens of thousands of references to objects held by clients of interfaces at a single host, into a single "ping" function, in order to minimise bandwidth utilisation. 11. What is the use of COM? Microsoft COM (Component Object Model) technology in the Microsoft Windows-family of Operating Systems enables software components to communicate. COM is used by developers to: create re-usable software components link components together to build applications take advantage of Windows services 12. Explain the steps or phases involved in implementing .NET remoting applications with an example. The steps involved in implementing .NET remoting applications: Create a Remotable Object:- A remotable object is nothing more than an object that inherits from MarshalByRefObject. The following sample demonstrates a simple class hello world. using System; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp; namespace Remoting {

Page |4
// Sample remote object public class SampleObject : MarshalByRefObject { // Constructor public SampleObject() { } // Return a Hello world message public string HelloWorld() { return Hello World!; } } } Create a Server to Expose the Remotable Object:- We need to create a server object that will act as a listener to accept remote object requests. For this example we will use the TCP/IP channel. using System; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp; namespace Remoting { // Sample server public class SampleServer { public static int Main(string [] args) { // Create an instance of a channel TcpChannel channel = new TcpChannel(8080); ChannelServices.RegisterChannel(channel); // Register with the name HelloWorld RemotingConfiguration.RegisterWellKnownServiceType( typeof(SampleObject), HelloWorld, WellKnownObjectMode.SingleCall ); System.Console.WriteLine(Press the enter to exit...); System.Console.ReadLine(); return 0; } } } Create a Client To Use the Remotable Object:- Now that we have our remotable object and a server object to listen for requests, let us create a client to use it. using System; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp; namespace Remoting { // Sample client public class SampleClient { public static int Main(string [] args) { // Create a channel for communicating with remote object // No port is specified on the client TcpChannel chan = new TcpChannel(); ChannelServices.RegisterChannel(chan); // Create an instance of the remote object

Page |5
SampleObject obj = (SampleObject) Activator.GetObject( typeof(Remoting.SampleObject),tcp://localhost:8080/HelloWorld ); // Use the object if( obj.Equals(null) ) { System.Console.WriteLine(Error: Cannot locate server); } else { Console.WriteLine(obj.HelloWorld()); } return 0; } } } Test the Remoting Sample:- Once we have created all the above code and successfully compiled each of them, we are ready to run it. Assuming we chose a free TCP/IP port for the service, start the server executable. After the server successfully starts it will display in a console window the message Press the enter key to exit. The server is listening so we are now ready to run the client. Executing the client should result in Hello World! being displayed in a separate console window. The client window will then close while the server remains open and available.

13. Explain different features of .NET. The different features of .NET are: It is developed with new set of API which enhances backward compatibility C# is a new language designed from scratch with .NET and for .NET platform. .NET platform supports object-oriented programming The .NET framework has Visual Studio.Net which is the upgradation of Visual Studio. The Visual Studio.Net has well built debugging feature, simplicity and vast controls. 14. List out the objectives of .Net framework? The Objectives of .NET Framework are: To provide an object-oriented programming environment whether object code is stored and executed locally, or executed remotely. To provide a code-execution environment that minimizes software deployment and versioning conflicts. To provide a code-execution environment that guarantees safe execution of code, including code created by an unknown or semi-trusted third party. To provide a code-execution environment that eliminates the performance problems of scripted or interpreted environments. To make the developer experience consistent across widely varying types of applications, such as Windows-based applications and Web-based applications. To build all communication on industry standards to ensure that code based on the .NET Framework can integrate with any other code. 15. Mention any four languages integrated with .NET. Four languages integrated with .NET are: C# C++ J++ VB.NET 16. What is ADO.NET? Why it is used in .NET? ADO.NET is the technology that is used for accessing databases. .NET has improved that kind of programming dramatically from an ease-of-use standpoint, through some features like strongly typed database. It has greatly simplified and enhanced capability of programming with databases. ADO.NET has been added new features like communicating with data sources which is made easy. ADO.NET is now the subset of .NET Base Classes.

Page |6
17. What does ADO stands for in ADO .NET? ADO in ADO.NET stands for ActiveX Data Object. 18. Write a program to show the demonstration of ADO.NET? Here is some sample code to execute a simple query. string connectionString = Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Samples\\Employee.mdb; OleDbConnection myConnection = new OleDbConnection( ConnectionString ); myConnection.Open(); string query = insert into EMPLOYEE_TABLE (EmployeeID, Name, Address) VALUES (101, John, 3960 CliffValley Way); OleDbCommand myCommand = new OleDbCommand(); myCommand.CommandText = query; myCommand.Connection = myConnection; myCommand.ExecuteNonQuery(); myConnection.Close(); The above code executes a SQL statement and returns no data from database. We are calling the method ExecuteNonQuery() on the command object. If we have a select ... statement which returns data from database, we cannot use the ExecuteNonQuery() method. 19. Explain in detail ADO.NET architecture. (Give the overall concept of ADO.Net with the help of figures) The ADO.NET components have two central components - the DataSet, and the .NET data provider. The .NET data provider is a set of components including the Connection, Command, DataReader, and DataAdapter objects. The ADO.NET DataSet is the core component of the disconnected architecture of ADO.NET. The DataSet is explicitly designed for data access independent of any data source. It can be used with multiple and different data sources, used with XML data, or used to manage data local to the application. The other core element of the ADO.NET architecture is the .NET data provider, whose components (Connection, Command, DataReader, and DataAdapter) are explicitly designed for data manipulation and forward-only, read-only access to data. The following diagram illustrates the components of ADO.NET architecture.

20. What is ASP. NET? ASP is a Microsoft Technology and it stands for Active Server Pages. ASP is a server side scripting technology that enables scripts (embedded in HTML pages) to be executed by an Internet server. ASP.NET is the next generation ASP. It is a part of the .NET Framework. It is a unified Web development platform that provides the services necessary for us to build enterprise Web applications. It also allows us to take full advantage of the features of the common language runtime, such as type safety, inheritance, language interoperability, and versioning. 21. Write an ASP. NET program to demonstrate handling of server control events. // exam6.aspx <html> <head>

Page |7
<link rel=stylesheethref=intro.css> </head> <script language=C# runat=server> void SubmitBtn_Click(Object sender, EventArgs e) { Message.Text = Hi + HttpUtility.HtmlEncode(Name.Text) + , you selected: + Category.SelectedItem; } </script> <body> <center> <form action=exam6.aspx method=post runat=server> <asp:adrotator AdvertisementFile=ads.xml BorderColor=black BorderWidth=1 runat=server/> <h3> Name: <asp:textbox id=Name runat=server/> Category: <asp:dropdownlist id=Category runat=server> <asp:listitem>psychology</asp:listitem> <asp:listitem>business</asp:listitem> <asp:listitem>popular_comp</asp:listitem> </asp:dropdownlist> </h3> <asp:button text=Lookup OnClick=SubmitBtn_Click runat=server/> <p> <asp:label id=Message runat=server/> </form> </center> </body> </html> // ads.xml file <Advertisements> <Ad> <ImageUrl>images/banner1.gif</ImageUrl> <NavigateUrl>http://www.microsoft.com</NavigateUrl> <AlternateText>Alt Text</AlternateText> <Keyword>Computers</Keyword> <Impressions>80</Impressions> </Ad> <Ad> <ImageUrl>images/banner2.gif</ImageUrl> <NavigateUrl>http://www.microsoft.com</NavigateUrl> <AlternateText>Alt Text</AlternateText> <Keyword>Computers</Keyword> <Impressions>80</Impressions> </Ad> <Ad> <ImageUrl>images/banner3.gif</ImageUrl> <NavigateUrl>http://www.microsoft.com</NavigateUrl> <AlternateText>Alt Text</AlternateText> <Keyword>Computers</Keyword> <Impressions>80</Impressions> </Ad> </Advertisements> 22. Write a program to display Welcome to ASP.NET 8 times in increasing order of their font size using ASP.NET. // exam2.aspx <%@ Page Language=C#%>//This line specify that the C# language is used for coding

Page |8
<html> <head> <link rel=stylesheethref=intro.css> </head> <body> <center> <form action=exam2.aspx method=post> <h3> Name: <input id=Name type=text> Category: <select id=Category size=1> <option>psychology</option> <option>business</option> <option>popular_comp</option> </select> </h3> <input type=submit value=Lookup> <p> <% for (int i=0; i <8; i++) { %> <font size=<%=i%>> Welcome to ASP.NET </font> <br> <% }%> </form> </center> </body> </html> 23. What does ASP stands for? ASP stands for Active Server Pages. 24. What is scripting language? Name some scripting languages used in .NET? A scripting language or script language is a programming language that supports the writing of scripts, programs written for a software environment that automate the execution of tasks which could alternatively be executed one-by-one by a human operator. Some scripting languages used in .NET are: C# C++ J++ VB.NET etc 25. What does XML stands for? Explain what is the use of XML in .NET? XML stands for EXtensible Markup Language. XML is the tool that is used automatically to serialize the request and sent it using HTTP across the Internet to the Web service, if we are developing code in the .NET Framework. The Web service calculates the result, and that result is serialized into XML to get sent back to the consumer. 26. Does .NET platform support mixed language interoperability. Yes, .NET platform supports mixed language interoperability. 27. What is the role of IIS server? IIS fulfills the role of the Web server, responding to requests for files from Web clients such as IE, and logging activity. IIS maintains information about the location of content files, what security identities have access to those files, how content files are separated into applications, and what URLs are mapped to those applications. IIS can communicate with software such as Microsoft SharePoint, Microsoft Visual Studio.NET, and Web Distributed Authoring and Versioning (WebDAV) to make Web content creation fast and easy. 28. Explain working of switch statement. A switch statement executes the statements that are associated with the value of a given expression, or default of statements if no match exists. The example demonstrates the switch usage how this statement switches on the number of arguments provided.

Page |9
if (Boolean_expression) { // if block statements } if (Boolean_expression) { // if block is executed if Boolean_expression is true } else { // else block is executed if Boolean_expression is false } class TestSwitch { static void Main(string[] args) { switch (args.Length) { case 0: Console.WriteLine(No arguments were provided); break; case 1: Console.WriteLine(One arguments was provided); break; default: Console.WriteLine(,0- arguments were provided, args.Length); break; } } } The switch expression must be an integer type, char or a string. The case labels have to be constants. The end of a case statement must explicitly state where to go next. The break statement takes the control to go out of switch statement. 29. Explain different types of arrays present in C# with an example. An array is a data structure that contains a number of variables called the elements of the array. The array elements are accessed through indexes. All of the array elements must be of the same type. Array elements can be of any type, including an array type. Array types are reference types derived from the abstract base type System.Array. Different types of arrays are: Single-Dimensional Arrays Multidimensional Arrays Jagged Arrays Passing Arrays Using ref and out For example, the array myArray is declared in the caller (the Main method), and initialized in the FillArray method. Then, the array elements are returned to the caller and displayed. public static void MyMethod(out int[] arr) { arr = new int[10]; // definite assignment of arr } public static void MyMethod(ref int[] arr) { arr = new int[10]; // arr initialized to a different array } using System; class TestOut {

P a g e | 10
static public void FillArray(out int[] myArray) { // Initialize the array: myArray = new int[5] {1, 2, 3, 4, 5}; } static public void Main() { int[] myArray; // Initialization is not required // Pass the array to the callee using out: FillArray(out myArray); // Display the array elements: Console.WriteLine(Array elements are:); for (int i=0; i < myArray.Length; i++) Console.WriteLine(myArray[i]); } } The output will be Array elements are: 1 2 3 4 5 30. What do you mean by Jagged Arrays? Explain with an example. A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes. A jagged array is sometimes called an array-of-arrays. This example builds an array, myArray, whose elements are arrays. Each one of the array elements has a different size. Console.Write(,0-, myJaggedArray*0+*1,0+); using System; public class JaggedArrayDemonstration { public static void Main() { // Declare the Jagged array of two elements: int[][] myArray = new int[2][]; // Initialize the elements: myArray[0] = new int[5] {1,3,5,7,9}; myArray[1] = new int[4] {2,4,6,8}; // Display the array elements: for (int i=0; i < myArray.Length; i++) { Console.Write(Element(,0-): , i); for (int j = 0 ; j < myArray[i].Length ; j++) Console.Write(,0-,1-, myArray*i+*j+, j == (myArray[i].Length-1) ? : ); Console.WriteLine(); } } } The output will be Element(0): 1 3 5 7 9 Element(1): 2 4 6 8

P a g e | 11
31. Write a note on multidimensional arrays. Arrays can have more than one dimension. For example, the following declaration creates a two dimensional array of four rows and two columns: int[,] myArray = new int[4,2]; Also it can create an array of three dimensions, 4, 2, and 3, as show below: int[,,] myArray = new int [4,2,3]; These arrays are known as multi-dimensional arrays. In this example, a two-dimensional array is initialized and passed to the PrintArray method, where its elements are displayed. using System; public class ArrayClass { static void PrintArray(int[,] s) { // Display the array elements: for (int i=0; i < 4; i++) for (int j=0; j < 2; j++) Console.WriteLine(Element(,0-,,1-)=,2-,i,j,s*i,j+); } public static void Main() { // Pass the array as a parameter: PrintArray(new int[,] {{1,2}, {3,4}, {5,6}, {7,8}}); } } The output will be Element(0,0)=1 Element(0,1)=2 Element(1,0)=3 Element(1,1)=4 Element(2,0)=5 Element(2,1)=6 Element(3,0)=7 Element(3,1)=8 32. Write a note on Single dimensional arrays. Single-dimensional arrays are used to store number of items of a predefined type. All items in a single dimension array are stored in a row starting from 0 to the size of array - 1. In the following example, a string array is initialized and passed as a parameter to the PrintArray method, where its elements are displayed: using System; public class ArrayClass { static void PrintArray(string[] s) { for (int i = 0 ; i < s.Length ; i++) Console.Write(s*i+ + ,0-, i < s.Length - 1 ? : ); Console.WriteLine(); } public static void Main() { // Declare and initialize an array: string[] WeekDays = new string [] ,Sun,Sat,Mon,Tue,Wed,Thu,Fri-; // Pass the array as a parameter: PrintArray(WeekDays);

P a g e | 12
} } The output will be Sun Sat Mon Tue Wed Thu Fri 33. How does string handle in C#? Explain. In C#, when we create a string, we instantiate a System.String object. In addition to its instance members, the System.String class has quite a few important static methods. The string type is immutable. This means that once it has been created, a string cannot be changed. No characters can be added or removed from it, nor can its length be changed. But let us have a look at below piece of code Employee Name: Joe Employee destructor executed. string str = I am going to have a lot of fun; str += with Dudley this summer. ... ; str += The End; In this example, an instance of str has been created, and a literal string value assigned to it three times. The statement that the type is immutable means that an instance cannot be edited but it can be assigned. 34. Compare the features of C++ with C# programming. / List out differences between C# and C++. Differences between C++ and C# are: C# is purely object-oriented language, whereas C++ support object-oriented programming. Arrays: The syntax of declaring C# arrays is different from that of C++ arrays. The tokens *+ appear following the array type in C#. The bool type in C#: There is no conversion between the bool type and int. The long type: In C#, the long data type is 64 bits, while in C++, it is 32 bits. The struct type: In C#, classes and structs are semantically different. A struct is a value type, while a class is a reference type. The switch statement: Unlike the C++ switch statement, C# does not support fall through from one case label to another. The delegate type: Delegates are roughly similar to function pointers in C++, but they are typesafe and secure. Preprocessor directives are used for conditional compilation. No header files are used in C#. C# operators: C# supports additional operators such as is and typeof. It also introduces different functionality of some logical operators. The Main method is declared differently from the main function in C++. The usage of the command-line arguments is also different. Method parameters: C# supports ref and out parameters, which are used instead of pointers in passing parameters by reference. Pointers are allowed in C# but only in unsafe mode. Overloading operators is performed differently in C#. Strings: C# strings are different from C++ strings. The foreach keyword allows you to iterate through arrays and collections. No global methods or variables in C#: Methods and variables must be contained within a type declaration (such as class or struct). No header files or #include directives in C#: The using directive is used to reference types in other namespaces without fully qualifying the type names. Destructors: In C#, you dont have control over when a destructor is called because destructors are called automatically by the garbage collector. Constructors: Unlike C++, if you dont provide a class constructor in C#, a default constructor is automatically generated for you. The default constructor initializes all the fields to their default values. C# does not support bit fields. 35. What is the use of attributes in C# programming? C# is an imperative language, but like all imperative languages it does have some declarative elements. For example, the accessibility of a method in a class is specified by declaring it public, protected, internal, protected internal, or private. C# generalizes this capability, so that programmers can invent new kinds of declarative information, attach this declarative information to various program entities, and retrieve this declarative information at run-time. Programs specify this additional declarative information by defining and using attributes.

P a g e | 13
36. Explain inheritance with an example? How does C# supports inheritance? Classes can inherit from another class. This is accomplished by putting a colon after the class name when declaring the class, and naming the class to inherit fromthe base classafter the colon, as follows: public class A { public A() { } } public class B : A { public B() { } } The new classthe derived classthen gains all the non-private data and behavior of the base class in addition to any other data or behaviors it defines for itself. C# classes support single inheritance, and the type object is the ultimate base class for all classes. The example shows a class A that implicitly derives from object. class Employee { private static DataSet ds; static Employee() { ds = new DataSet(...); } public string Name; public decimal Salary; ... } using System; class A { public void F() , Console.WriteLine(Inside A.F); } class B: A { public void G() , Console.WriteLine(Inside B.G); } class Test { static void Main() { B b = new B(); b.F(); // Inherited from A b.G(); // Introduced in B A a = b; // Treat a B as an A a.F(); } } shows a class B that derives from A. The class B inherits As F method, and introduces a G method of its own. Methods, properties, and indexers can be virtual, which means that their implementation can be overridden in derived classes. 37. How does C# supports multiple inheritance? / How does C# supports multilevel inheritance? Explain. (What are interfaces? Explain with an example.) C# supports multiple inheritance through the use of Interfaces. The interface keyword declares a reference type that has abstract members. Interfaces are used to define a contract; a class or struct that implements the interface must obey to this contract. Example: interface IControl { void Paint(); } interface ITextBox: IControl //ITextBox inherits IControl { void SetText(string text); } interface IListBox: IControl //IListBox inherits IControl { void SetItems(string[] items); }

P a g e | 14
interface IComboBox: ITextBox, IListBox {} 38. Does C# support pointers? The C# language has omitted pointers as a data type. C# instead provides references and the ability to create objects that are managed by a garbage collector. This design contributes in making C# a much safer language than C or C++. 39. Write a program in C# to display Welcome to C Sharp. Explain the program. / Write a program in C # to display Welcome to World of C sharp Explain the program. // This is a program to display a message public class Welcome { public static void Main() { //Print Hello World System.Console.WriteLine("Welcome to the world of C Sharp"); } } The important points to be noted in this program are: Comments:- used for proper documentation of the code The first line is a comment // This is a program to display a message The Main Method:- in this control starts and ends. We can create objects and execute other methods within this Main method Input and Output:- In the above Welcome program there is only one output statement, no input statements. The statement: System.Console.WriteLine(Welcome to the world of C Sharp); uses the WriteLine method, of the Console class which resides in the .NET run-time library. Compilation and Execution:- The compile and execution commands given here are for command line compiler. 40. Write a program to C# to add two matrices. public static Matrix operator +(Matrix mat1, Matrix mat2) { Matrix newMatrix = new Matrix(); for (int x=0; x < DimSize; x++) for (int y=0; y < DimSize; y++) newMatrix[x, y] = mat1[x, y] + mat2[x, y]; return newMatrix; } 41. Write a program in C# to check a given string is palindrome or not. using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string str=string .Empty ; Console.WriteLine("Enter a String"); string s = Console.ReadLine(); int i = s.Length; //we can get the Length of string by using Length Property for (int j=i -1; j >= 0; j--)

P a g e | 15
{ str = str + s[j ]; } if (str == s) { Console.WriteLine(s + " is palindrome"); } else { Console.WriteLine(s + " is not a palindeome"); } Console.WriteLine(str); Console.Read(); } } } 42. Explain different string functions supported by C#? Different string functions supported by C# are: Join and Split Join takes a String array and a separator string and produces a single string with one separator between each element in the array. Split does the opposite, splitting a string made up of several elements separated by a separator. string commatext = "alpha,bravo,charlie"; string[] words = commatext.Split(',') ; string dashed = string.Join("---", words) ; Console.WriteLine("Dashed join is {0}", dashed) ; PadLeft and PadRight These two functions pad a string to the left or right with to the specified length. By default the character is a space but an overload lets us specify an alternative char. string y = x.PadRight(x.Length + 10) ; StartsWith and EndsWith Both methods return true or false if a string starts or ends with the specified string. if (s1.StartsWith(" ")) Console.WriteLine("S1 starts with spaces") ;

43. Write the general structure of C# programming. C# program can consist of one or more files. Each file can contain one or more namespaces. A namespace contains group of related types such as classes, structs, interfaces, enumerations, and delegates. Namespaces may be nested. // A skeleton of a C# program using System; namespace Namespace1 { class Class1 { } struct Struct1 { } interface Interface1 { } delegate int Delegate1(); enum Enum1 { } namespace Namespace2

P a g e | 16
{ } class Class2 { public static void Main(string[] args) { } } } 44. Mention the different preprocessor directives of C#. Give an example each. While the compiler does not have a separate preprocessor, the directives are processed as if there was a preprocessor. These directives are used during conditional compilation. These are preprocessor directives. #if #if, begins a conditional directive for testing a symbol, to see if they evaluate to true e.g. #define DEBUG #define VC_V6 using System; public class MyClass { public static void Main() { #if (DEBUG && !VC_V6) Console.WriteLine("DEBUG is defined"); #elif (!DEBUG && VC_V6) Console.WriteLine("VC_V6 is defined"); #elif (DEBUG && VC_V6) Console.WriteLine("DEBUG and VC_V6 are defined"); #else Console.WriteLine("DEBUG and VC_V6 are not defined"); #endif } } The output will be, DEBUG and VC_V6 are defined #else #else, creates a compound conditional directive, such that, if none of the expressions in the preceding #if or #elif directives did not evaluate to true, the compiler will evaluate all code between #else and the subsequent #endif. #elif #elif, creates a compound conditional directive, it evaluates if neither the preceding #if nor any preceding #elif directive expressions evaluate to true. #endif #endif specifies the end of a conditional directive, which began with the #if directive. #define #define, defines a symbol by using the symbol as the expression passed to the #if directive, the expression will evaluate to true. #undef #undef, undefines a symbol by using the symbol as the expression in a #if directive, the expression will evaluate to false. e.g. #undef DEBUG

P a g e | 17
using System; public class MyClass { public static void Main() { #if DEBUG Console.WriteLine("DEBUG is defined"); #else Console.WriteLine("DEBUG is not defined"); #endif } } The output will be, DEBUG is not defined #warning #warning, generates a level one warning from a specific location in our code. e.g. #define DEBUG public class MyClass { public static void Main() { #if DEBUG #warning DEBUG is defined #endif } } #error #error, generates an error from a specific location in your code. e.g. #define DEBUG public class MyClass { public static void Main() { #if DEBUG #error DEBUG is defined #endif } } #line #line, modifies the compilers line number and the file name output for errors and warnings. public class MyClass2 { public static void Main() { #line 200 int i; // error or warning will be: CS0168 on line 200 #line 8 char c; // error or warning will be: CS0168 on line 8 } }

P a g e | 18
45. Write a program in C# to calculate factorial of given number and explain the program. using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Factorial { class Program { static void Main(string[] args) { Console.WriteLine(" Give me the number you want the factorial: \n "); long a = Convert.ToInt64(Console.ReadLine()); Console.WriteLine(" The factorial of given number is: " + Factorial(a)); Console.ReadKey(); } public static long Factorial(long number) { if (number <= 1) return 1; else return number * Factorial(number - 1); } } } 46. What is constructor? Explain different types of constructors used in C# program. (Static constructors) Whenever a class or struct is created, its constructor is called. A class or struct may have multiple constructors that take different arguments. Constructors enable the programmer to set default values, limit instantiation, and write code that is flexible and easy to read. There are two types of constructor: An instance constructor is a member that implements the actions required to initialize an instance of a class. e.g. using System; class Point { public double x, y; // Instance constructor public Point() { this.x = 0; this.y = 0; } //Parameterized Instance constructor public Point(double x, double y) { this.x = x; this.y = y; } public static double Distance(Point a, Point b) { double xdiff = a.x - b.x; double ydiff = a.y - b.y; return Math.Sqrt(xdiff * xdiff + ydiff * ydiff); } public override string ToString() { return string.Format((,0-, ,1-), x, y);

P a g e | 19
} } class Test { static void Main() { Point a = new Point(); Point b = new Point(3, 4); double d = Point.Distance(a, b); Console.WriteLine(Distance from ,0- to ,1- is ,2-, a, b, d); } } shows a Point class that provides two public instance constructors, one of which takes no arguments, while the other takes two double arguments. A static constructor is a member that implements the actions required to initialize a class. Static constructors cannot have parameters, they cannot have accessibility modifiers, and they cannot be called explicitly. The static constructor for a class is called automatically. e.g. class Employee { private static DataSet ds; static Employee() { ds = new DataSet(...); } public string Name; public decimal Salary; ... }

47. What are methods in C#? / Write a note on Methods. A method is a member that implements a computation or action that can be performed by an object or class. Methods have a list of formal parameters, a return value and are either static or non-static. Static methods are accessed through the class. Non-static methods, which are also called instance methods, are accessed through instances of the class (objects). The example class Color { internal ushort redPart; internal ushort bluePart; internal ushort greenPart; public Color(ushort red, ushort blue, ushort green) { redPart = red; bluePart = blue; greenPart = green; } public static readonly Color Red = new Color(0xFF, 0, 0); public static readonly Color Blue = new Color(0, 0xFF, 0); public static readonly Color Green = new Color(0, 0, 0xFF); public static readonly Color White = new Color(0xFF, 0xFF, 0xFF); } using System; public class Stack { public static Stack Clone(Stack s) {...} public static Stack Flip(Stack s) {...}

P a g e | 20
public object Pop() {...} public void Push(object o) {...} public override string ToString() {...} ... } class Test { static void Main() { Stack s = new Stack(); for (int i = 1; i < 10; i++) s.Push(i); Stack flipped = Stack.Flip(s); Stack cloned = Stack.Clone(s); Console.WriteLine(Original stack: + s.ToString()); Console.WriteLine(Flipped stack: + flipped.ToString()); Console.WriteLine(Cloned stack: + cloned.ToString()); } } shows a Stack that has several static methods (Clone and Flip) and several instance methods (Pop, Push, and ToString). 48. Explain methods with passing value and by passing references. Passing by value The parameter modifiers ref and out relate to how the parameter is passed into the method. Where neither of these modifiers is used, the parameter is passed in by value. In this case, when the method is called the value given is copied to the variable specified in the method declaration. e.g. public static void Main() { int a = 0; change(a); } public static void change(int b) { b = 5; } Passing by reference Where a variable is passed by reference, the ref modifier must be used both in the method definition argument list and the method invocation. e.g. public static void Main() { int a = 0; change(ref a); // After this method invocation, a=5 } public static void change (ref int b) { b = 5; } 49. Explain different methods for passing arguments. Different methods for passing arguments: Passing by value The parameter modifiers ref and out relate to how the parameter is passed into the method. Where neither of these modifiers is used, the parameter is passed in by value. In this case, when the method is called the value given is copied to the variable specified in the method declaration. e.g.

P a g e | 21
public static void Main() { int a = 0; change(a); } public static void change(int b) { b = 5; } Passing by reference Where a variable is passed by reference, the ref modifier must be used both in the method definition argument list and the method invocation. e.g. public static void Main() { int a = 0; change(ref a); // After this method invocation, a=5 } public static void change (ref int b) { b = 5; } output parameters Where a method parameter is defined (and invoked) using the out modifier, it is passed by reference. The difference between the out and the ref modifier is this: a parameter modified by the out keyword need not be assigned a value before being passed into the method, but must be assigned a value in the method before it is returned. e.g. public static void Main() { bool b; int c = change(5, out b); } public static int change (int a, out bool b) { b=false; if (a>0) b=true; return (2*a);} The params modifier One can pass an arbitrary number of types to a method by declaring a parameter array with the params modifier. Types passed as params are all passed by value. e.g. public static void Main() { double a = 1; int b = 2; int c = 3; int d = 4; int e = total(a, b, c, d); } public static int total(double a, params int[] intArr) { int sum = 0; for (int i=0; i < intArr.Length; i++) sum += intArr[i]; return sum;

P a g e | 22
} Return Type Methods can either return a type or not. A method that does not return a type must give its return type as void. A method that does return a type must name the type returned. e.g. public static int exampleMethod() { int i = 0; ... return i; } 50. What is method overloading? Give an example. Methods can be overloaded, which means that multiple methods may have the same name. The method with matching signature is called. The example using System; class Test { static void Func() { Console.WriteLine(Func()); } static void Func(object o) { Console.WriteLine(Func(object)); } static void Func(int value) { Console.WriteLine(Func(int)); } static void Func(ref int value) { Console.WriteLine(Func(ref int)); } static void Func(int a, int b) { Console.WriteLine(Func(int, int)); } static void Func(int[] values) { Console.WriteLine(Func(int*+)); } static void Main() { Func(); Func(1); int i = 10; Func(ref i); Func((object)1); Func(1, 2); Func(new int[] {1, 2, 3}); } } shows a class with a number of methods called Func. The output produced is Func()

P a g e | 23
Func(int) Func(ref int) Func(object) Func(int, int) Func(int[]) 51. What are the different methods supported by System.Object class? Give an example for each. (What is the use of Get Type ( ) method?) System.Object class is the ultimate base class that all types directly or indirectly derive from. The object class allows us to build generic routines, provides Type System Unification, and enables working with groups collections. The different methods supported by System.Object class are: The Equals Method It provides a default implementation that compares two reference type objects for reference equality. e.g. using System; class Employee { string e_name; public Employee(string name) { e_name = name; } } class EqualsDemonstration { static void Main() { EqualsDemonstration eqDemo = new EqualsDemonstration(); eqDemo.InstanceEqual(); Console.ReadLine(); } public void InstanceEqual() { string name = Joe; Employee employee1 = new Employee(name); Employee employee2 = new Employee(name); // comparing references of separate instances bool isEqual = employee1.Equals(employee2); Console.WriteLine(employee1 == employee2 - ,0-, isEqual); employee2 = employee1; // comparing references of the same instance isEqual = employee1.Equals(employee2); Console.WriteLine(employee1 == employee2 - ,0-, isEqual); } } The output will be employee1 == employee2 False employee1 == employee2 True The ReferenceEquals Method The Equals and ReferenceEquals methods are semantically equivalent, except that the ReferenceEquals works only on object instances. e.g. using System; class Employee {

P a g e | 24
string e_name; public Employee(string name) { e_name = name; } } class ReferenceEqualsDemo { static void Main() { ReferenceEqualsDemo refEqDem = new ReferenceEqualsDemo(); refEqDem.InstanceEqual(); Console.ReadLine(); } public void InstanceEqual() { string name = Joe; Employee employee1 = new Employee(name); Employee employee2 = new Employee(name); // comparing separate instances bool isEqual = Object.ReferenceEquals(employee1, employee2); Console.WriteLine(employee1 == employee2 - ,0-, isEqual); employee2 = employee1; // comparing the same instance isEqual = Object.ReferenceEquals(employee1, employee2); Console.WriteLine(employee1 == employee2 - ,0-, isEqual); } } The output will be employee1 == employee2 False employee1 == employee2 True The ToString Method It returns the string representation of a type. e.g. using System; class Employee { string e_name; public Employee(string name) { e_name = name; } // If ToString() is not overridden, the output of this program will be Employee. public override string ToString() { return String.Format(*Employee: ,0-+, e_name); } } class ToStringDemonstration { static void Main() { Employee emp = new Employee(Joe); Console.WriteLine(emp.ToString()); Console.ReadLine();

P a g e | 25
} } The output will be [Employee: Joe] The GetType Method It returns a Type object, describing the object it was called on. It can then be used to extract type member data like methods and fields that may subsequently be used for late-bound method invocations. e.g. using System; class Employee { } class GetTypeDemonstration { static void Main() { object emp1 = new Employee(); Employee emp2 = new Employee(); Console.WriteLine(emp1.GetType()); Console.WriteLine(emp2.GetType()); Console.ReadLine(); } } The output will be Employee Employee The GetHashCode Method It makes any object usable in a Hashtable or any hashing algorithm. e.g. using System; class Employee { string e_name; public Employee(string name) { e_name = name; } public override int GetHashCode() { string uniqueString = ToString(); return uniqueString.GetHashCode(); } public override string ToString() { return String.Format(*Employee: ,0-+, e_name); } } class GetHashCodeDemonstration { static void Main() { Employee emp = new Employee(Joe); Console.WriteLine(emp.GetHashCode()); Console.ReadLine();

P a g e | 26
} } The output will be -275241189 The MemberwiseClone Method Whenever we need to create a bitwise copy (shallow copy) of our type, the MemberwiseClone method is used. e.g. using System; public class Address {} class Employee { Address e_address = new Address(); string e_name; public Employee(string name) { e_name = name; } public Employee ShallowCopy() { return (Employee)MemberwiseClone(); } public Address EmployeeAddress { get { return e_address; } } } class MemberwiseCloneDemonstration { static void Main() { Employee emp1 = new Employee(Joe); Employee emp2 = emp1.ShallowCopy(); // compare Employee references bool isEqual = Object.ReferenceEquals(emp1, emp2); Console.WriteLine(emp1 == emp2 - ,0-, isEqual); //compare reference of Address object in each Employee object isEqual = Object.ReferenceEquals(emp1.EmployeeAddress, emp2.EmployeeAddress); Console.WriteLine(emp1.EmployeeAddress == emp2.EmployeeAddress ,0-, isEqual); Console.ReadLine(); } } The output will be emp1 == emp2 False emp1.EmployeeAddress == emp2.EmployeeAddress True The Finalize Method Although the object class has a Finalize method, it is not available to C# programs in that form. Instead, we can use what is called a destructor in C#, which is synonymous with the Finalize method. e.g. using System;

P a g e | 27
class Employee { string e_name; public Employee(string name) { e_name = name; Console.WriteLine(Employee Name: ,0-, e_name); } ~Employee() { Console.WriteLine(Employee destructor executed.); } } class DestructorDemonstration { static void Main() { Employee emp = new Employee(Joe); } } The output will be Employee Name: Joe Employee destructor executed. 52. What is Destructor? Destructors are used to destruct instances of classes. Destructors cannot be defined in structs. They are only used with classes. A class can only have one destructor. Destructors cannot be inherited or overloaded. Destructors cannot be called. They are invoked automatically. A destructor does not take modifiers or have parameters. Example: class Car { ~Car() // destructor { // cleanup statements... } } 53. What are Variables? How many different variables are there in C#? Define each. (What are instance variables?) Variables represent storage locations. Every variable has a type that determines what kind of data can be stored in the variable. C# variable declaration have following syntax: [optional_modifier] datatype identifier; Where optional_modifier is accessibility form There are seven categories of variables: Static variables: Variables with a static modifier. Instance variables: Variables declared without static modifier. Array elements: The array is a container that has a list of storage locations for a specified type. Value parameters: A parameter declared without a ref or out modifier Reference parameters: A parameter declared with a ref modifier is a reference parameter. Output parameters: A parameter declared with an out modifier is an output parameter. Local variables: A local variable is declared and exits within a block, a for-statement, a switch-statement, or using statement.

P a g e | 28
54. Explain the classes of C#. Class declarations are reference types. A class can inherit from another class, and can implement interfaces. Class members can include constants, fields, methods, properties, events, indexers, operators, instance constructors, destructors, static constructors, and nested type declarations. Each member has an associated accessibility, which controls the portion of program code that is able to access the member. The declared accessibility of a member can be one of the following:

The example using System; class MyClass { public MyClass() // Instance constructor { Console.WriteLine(Instance constructor); } public MyClass(int value) // Parameterized Instance constructor { MyField = value; Console.WriteLine(Instance constructor); } ~MyClass() // Destructor { Console.WriteLine(Destructor); } public const int MyConst = 20; public int MyField = 40; public void MyMethod() { Console.WriteLine(MyClass.MyMethod); } public int MyProperty { get { return MyField; } set { MyField = value; } } public int this[int index] { get { return 0; } set

P a g e | 29
{ Console.WriteLine(this*,0-+ = ,1-, index, value); } } public event EventHandler MyEvent; public static MyClass operator+(MyClass a, MyClass b) { return new MyClass(a.MyField + b.MyField); } internal class MyNestedClass {} } shows a class that contains properties, constant, field, event, indexed and method as members. 55. How do name spaces and types in C# have unique names? Give example. Fully Qualified Names describe the logical hierarchy of the type or object. Namespaces and types always have unique names. For example, If there are 2 class with same name but are present in different namespaces then both the objects will have their unique fully qualified names. 56. Write a note on name spaces in C#. The namespace keyword is used to declare a scope. This namespace scope lets us organize code and gives us a way to create globally unique types. 57. What are different jump statements supported by C# ? Explain. Jump statements unconditionally transfer control. Different jump statements supported by C# are: break statement: exits the nearest enclosing switch, while, do, for, or foreach statement. continue statement: starts a new iteration of the nearest enclosing while, do, for, or foreach statement. goto statement: transfers control to a statement that is marked by a label. return statement: returns control to the caller function. throw statement: throws an exception. 58. List out important features of C#. Important features of C# language design are: C# is an elegant, simple, type-safe, object-oriented language. C# has the capability to build durable system-level components due to following features: Full COM/Platform support for existing code integration. Robustness through garbage collection and type safety. Security provided through good design. Full support of extensible metadata concepts. C# supports Language Interoperability and Platform Independence due to following features: Full interoperability with COM and .NET Framework services, through tight .NET Library Base classes. XML support for web-based component interaction. Versionability. 59. Expressions & Operators in C#. (Mention the three kinds of operators in C#) [Write the syntax of ternary operator.] An expression is a sequence of operators and operands that specifies computation and assigns the result to a variable. Expressions are constructed from operands and operators. The operators of an expression indicate which operations to perform. Examples for operators are +, -, *, /, etc. Examples for operands are literals, variables, and expressions. There are three kinds of operators: Unary operators: The unary operators operate on only one operand. For example: x, x++, etc. Binary operators: The binary operators operate on two operands. For example: x + y. Ternary operator: There is only one ternary operator, ?:. The ternary operator operates on three operands. For example: condition? true_exp: false_exp

P a g e | 30
60. Give any two statement of C#? C# provides a variety of statements. Two of them are: Blocks A block permits multiple statements to be written as group. A block consists of list of single statements enclosed in braces. { // Begin a block Bool flag; flag = true; CallFunction(flag); } // End a block The empty statement An empty statement (;) is used when there are no operations to perform, but requires a statement. Execution of an empty statement simply transfers control to the end point of the statement. while (WaitForAnEvent()) ; 61. Mention three advantages of C# . Three advantages of C# are: C# helps us to import a namespace and use the classes in a componentno COM plumbing or registry lookups required. C# provides operator overloading which is not available in VB.NET. C# allows us to access memory directly using unsafe code blocks. 62. Mention the four types of iteration statements in C#. Iteration statements repeatedly execute a block of statements. The number of iterations depends on the condition represented by boolean expression. The block of code will be iterated until the condition is true. There are four iteration statements in C#: while statement do statement for statement foreach statement 63. Explain how to use multiple threads in program with example. / What is the use of multiple threading? Explain. Software that requires user interaction must react to the users requests rapidly to provide a user friendly experience. At the same time, however, it must do the calculations necessary to respond to the user as fast as possible. If application uses only one thread of execution, then it may be difficult to process the entire request simultaneously and decrease the data processing time of application. In such cases multiple threads can be created to do the bits of work independently to increase applications responsiveness. e.g. using System; using System.Threading; public class A { // This method that will be called when the thread is started public void B() { while (true) { Console.WriteLine(A.B is running in its own thread.); } } }; public class Simple { public static int Main() { Console.WriteLine(Thread Start/Stop/Join Example);

P a g e | 31
A oA = new A(); // Create the thread object, passing in the A.B method // via a ThreadStart delegate. This does not start the thread. Thread oThread = new Thread(new ThreadStart(oA.B)); // Start the thread oThread.Start(); // loop until the started thread becomes alive while (!oThread.IsAlive); // Main thread sleeps for 1 ms untill oThread finishes its work Thread.Sleep(1); // oThread is stopped oThread.Abort(); // Wait until oThread finishes and Joins. oThread.Join(); Console.WriteLine(); Console.WriteLine(A.B has finished); try { Console.WriteLine(Try to restart the A.B thread); oThread.Start(); } catch (ThreadStateException) { Console.Write(ThreadStateException trying to restart A.B); Console.WriteLine(Aborted threads cannot be restarted.); } return 0; } } The Output will be Thread Start/Stop/Join Example A.B is running in its own thread. A.B is running in its own thread. A.B is running in its own thread. ... ... A.B has finished Try to restart the A.B thread ThreadStateException trying to restart A.B Aborted threads cannot be restarted. 64. What are the advantages of using multiple threads in program? (List out the disadvantages of multiple threading.) Advantages of Multiple Threads Communicate over a network, to a Web server and to a database. Perform operations that take a large amount of time. Distinguish tasks of varying priority. For example, a high-priority thread manages time-critical tasks, and a low-priority thread performs other tasks. Allow the user interface to remain responsive, while allocating time to background tasks. Disadvantages of Multiple Threads Memory requirement for the context information required by processes, Application Domain objects, and threads. Therefore, the number of processes, Application Domain objects, and threads which can be created is limited by memory availability. Keeping track of a large number of threads consumes significant processor time. If there are too many threads, then there will not be any significant advantage of threads. Controlling execution of an application with many threads can be a source of many bugs and it is very complex.

P a g e | 32

65. What is Threading? Operating systems use different process space for each process, and processes receive services for operating system separately. Threads are the basic unit to which an operating system allocates processor time, and more than one thread can run inside that process. 66. Explain exception handling techniques. Exceptions are handled by a try statement. When an exception occurs, the system searches for the nearest catch block that can handle the exception. Once a matching catch block is found, the control is transferred to the first statement of the catch block and the catch block executes. If no matching catch block or finally block is found, then the execution of the thread is terminated. List of catch blocks:

67. What is an exception? Given an example. An exception is any error condition or unexpected behavior encountered by a program in execution. Exceptions can be raised because of a fault in our code or in shared library or when operating system resources not being available or when unexpected conditions the CLR encounters and so on. Here is a C# example, which demonstrates the usage of try, catch, throw and finally statements. using System; using System.IO; public class ProcessFile

P a g e | 33
{ public static void Main() { try //Opens a text file. { FileStream fs = new FileStream(data.txt, FileMode.Open); StreamReader sr = new StreamReader(fs); string line; //Read from the file and output it to the console. line = sr.ReadLine(); Console.WriteLine(line); } catch(FileNotFoundException e) { Console.WriteLine(*Data File Missing+ ,0-, e); throw new FileNotFoundException(data.txt not exists,e); } finally { fs.Close(); } } } 68. Explain how to create user defined exceptions with an example. We can also create our own exception classes by deriving from the Exception class. When creating our own exceptions, it is also good practice to implement the three recommended common constructors. In the following example, a new exception class, EmployeeListNotFoundException, is derived from Exception. Three constructors are defined in the class, each taking different parameters. using System; public class EmployeeListNotFoundException: Exception { public EmployeeListNotFoundException() { } public EmployeeListNotFoundException(string message) : base(message) { } public EmployeeListNotFoundException(string message, Exception inner) : base(message, inner) { } } 69. Explain difference between bugs, errors and exceptions in program? Bug When the cause of the error is because of a mistake done by a developer, it is called a bug. For example, a declared file object may not be disposed, and may later cause a memory leak. Error An error may be invoked by an input made by the end user. For example, an invalid string may be entered in a Textbox that expects a number. Exception An exception may be a System Exception or an Application Exception. For example a file being parsed by the code has been deleted by someone from the location being searched, then a File Not Found exception may crop up. These errors are handled with Exception Handlers.

P a g e | 34
70. What is the function of CTS? Explain the classification of types in CTS with a diagram. / Give the classification of common data type system. Common Type System (CTS) is a standardized agreed set of basic data types. This system provides a way for language interoperability. Language Interoperability means that an object implemented in one language can call an object implemented in another language. Classification of types The CTS supports two categories: Value types:- Value types directly stores data in the variable. Value types can be built-in type, user-defined types, or enumerations. Reference types:- Reference types store a reference to the datas memory address. Reference types can be self-describing types, pointer types, or interface types. Self-describing types are further split into arrays and class types. The class types are user-defined classes, boxed value types, and delegates.

71. What is operator overloading? Explain with an example. Operator overloading permits user-defined operator implementations to be specified for operations where one or both of the operands are of a user-defined class or struct type. To overload an operator in a class, one defines a method using the operator keyword. For instance, the following code overloads the equality operator public static bool operator == ( Value a ,Value b) { return a.Int == b.Int } 72. What is data provider? Explain. A .NET data provider is used for connecting to a database, executing commands, and retrieving results. It is designed to be lightweight, creating a minimal layer between the data source and application code, increasing performance without sacrificing functionality. The following table outlines the four core components of .NET data provider.

P a g e | 35

73. What is a Data Set? Explain. The DataSet object is central to supporting disconnected, distributed data scenarios with ADO.NET. The DataSet is a memory resident representation of data that provides a consistent relational programming model regardless of the data source. The following illustration shows the DataSet object model.

74. Write a note on meta-data. (Explain why it is required) Metadata is binary information describing the program. When we compile our code into a PE file, metadata is inserted into one portion of the PE file, while the code is converted to IL and inserted into another portion of the PE file. Every type, member which are defined or referenced in a module is described within metadata. Metadata is required to: allow .NET languages to describe themselves in a language-neutral manner to give required information to CLR to perform much of its functionalities the CLR modules or components or other assemblies which want to communicate with each other uses these information stored in metadata to perform their tasks.

P a g e | 36
75. What is the role of system web? The System.Web namespace supplies classes and interfaces that enable browser and server communication. This namespace includes the HttpRequest class which provides extensive information about the current HTTP request, the HttpResponse class which manages HTTP output to the client, and the HttpServerUtility class which provides access to server-side utilities and processes. 76. Explain uses of system collections class. The System.Collections namespace contains interfaces and classes that define various collections of objects, such as lists, queues, bit arrays, hashtables and dictionaries.

77. What are assemblies? What are Static & Dynamic assemblies? Explain. Assembly is a basic element of packaging in .NET. An assembly consists of IL code, metadata that describes what is in the assembly, and any other files or information that the application needs to run, such as graphics and sound files. Assemblies can be static or dynamic. Static assemblies can include .NET types (interfaces and classes), as well as required resources for the assembly (bitmaps, JPEG files, resource files, and so on). Static assemblies are stored on disk in PE files. Dynamic assemblies are one which run directly from memory and are not saved to disk before execution. They can be saved disk after they have executed. 78. What are functionalities of CLR? Give the steps involved in managed execution process The functionalities of CLR: To enable the runtime to provide services to managed code, language compilers must emit metadata that describes the types, members, and references in their code. The runtime automatically handles object layout and manages references to objects, releasing them when they are no longer being used. The CLR makes it easy to design components and applications whose objects interact across languages.

P a g e | 37
The runtime uses metadata information to ensure that our component or application has the specified versions of everything it needs, which makes our code less likely to break due to some dependency.

The managed execution process includes the following steps: Choosing an appropriate language compiler. Compiling code to Microsoft intermediate language (MSIL or simply IL). Compiling IL to native code. At execution time, a just-in-time (JIT) compiler translates the IL into native machine code. During this compilation, code must pass a verification process that examines the IL and metadata to find out whether the code can be determined to be type safe. Executing code. The CLR provides the environment that enables execution to take place as well as a variety of services that can be used during execution. 79. With an example explain indexers. An indexer enables an object to be indexed in the same way as an array. The example using System; public class Stack { private Node GetNode(int index) { Node temp = first; while (index > 0) { temp = temp.Next; index ; } return temp; } public object this[int index] { get { if (!ValidIndex(index)) throw new Exception(Index out of range.); else return GetNode(index).Value; } set { if (!ValidIndex(index)) throw new Exception(Index out of range.); else GetNode(index).Value = value; } } ... } class Test { static void Main() { Stack s = new Stack(); s.Push(1); s.Push(2); s.Push(3); s[0] = 33; // Changes the top item from 3 to 33 s[1] = 22; // Changes the middle item from 2 to 22

P a g e | 38
s[2] = 11; // Changes the bottom item from 1 to 11 } } shows an indexer for the Stack class. 80. What is unsafe code? Explain. The use of pointers is rarely required in C#, but there are some situations that require them. In these cases using an unsafe context to allow pointers is warranted by the following cases: Dealing with existing structures on disk Advanced COM or Platform Invoke scenarios that involve structures with pointers in them Performance-critical code. In unsafe code it is possible to declare and operate on pointers, to perform conversions between pointers and integral types, to take the address of variables, and so forth. 81. What is the importance of automatic memory management? Explain with example. Manual memory management requires developers to manage the allocation and de-allocation of blocks of memory. Manual memory management can be both time-consuming and difficult. In C#, automatic memory management is provided so that developers are freed from this burdensome task. Automatic memory management increases code quality and enhances developer productivity without negative impact on either expressiveness or performance. The example: using System; public class Stack { private Node first = null; public bool Empty { get { return (first == null); } } public object Pop() { if (first == null) Console.Write("Can't Pop from an empty Stack."); else { object temp = first.Value; first = first.Next; return temp; } } public void Push(object o) { first = new Node(o, first); } class Node { public Node Next; public object Value; public Node(object value): this(value, null) {} public Node(object value, Node next) { Next = next; Value = value; } } } shows a Stack class implemented as a linked list of Node instances.

P a g e | 39
82. With the help of an example differentiate struct and class. Classes are reference types and structs are value types. Since classes are reference type, a class variable can be assigned null. But we cannot assign null to a struct variable, since structs are value type. When we instantiate a class, it will be allocated on the heap. When we instantiate a struct, it gets created on the stack. We will always be dealing with reference to an object (instance) of a class. But we will not be dealing with references to an instance of a struct (but dealing directly with them). When passing a class to a method, it is passed by reference. When passing a struct to a method, its passed by value instead of as a reference. We cannot have instance Field initializers in structs. But classes can have the same. e.g.: class MyClass { int myVar =10; // no syntax error. public void MyFun( ) { // statements } } struct MyStruct { int myVar = 10; // syntax error. public void MyFun( ) { // statements } } Classes can have explicit parameterless constructors. But structs cannot have the same. Classes must be instantiated using the new operator. But structs can be instantiated. Classes support inheritance.But there is no inheritance for structs. (structs dont support inheritance polymorphism) Since struct does not support inheritance, access modifier of a member of a struct cannot be protected or protected internal A class is permitted to declare a destructor. But a struct is not. Classes are used for complex and large set data. Structs are simple to use. 83. Explain Structs with an example. Structs are similar to classes, they represent data structures that can contain data members and also function members. Structs are value and a variable of a struct type directly contains the data of the struct. Structs are useful for small data structures. class Point { public int x, y; public Point() { x = 0; y = 0; } public Point(int x, int y) { this.x = x; this.y = y; } } class Test { static void Main() { Point[] points = new Point[100];

P a g e | 40
for (int i = 0; i < 100; i++) points[i] = new Point(i, i*i); } } 84. Define Delegates. A delegate is a C# language element that allows us to reference a method. For a C or C++ programmer, this is a familiar because a delegate is basically like a function pointer. However, unlike function pointers, delegates are object-oriented and type-safe. 85. What is boxing and unboxing? Explain with an example. Boxing and Unboxing is a central concept in a C# type system. When assigning a value type to an object, in the background, the system performs an extra operation referred to as Boxing. After a boxing operation has completed, a value type is considered boxed. Similarly, when copying a boxed value type back to a normal value type, in the background, the system performs another operation referred to as Unboxing. Given below is a piece of code shows a simple boxing/unboxing operation. int myValueType1 = 8; object myReferenceType = myValueType1; // myValueType is boxed int myValueType2 = (int) myReferenceType; // myValueType is unboxed 86. With a neat diagram explain the event handling process of win forms / web forms. With a Web Form, we have to use a browser. We can have browser to display a Web page that has some controls on it, and can have interaction with that Web page and Web service. ASP.NET provides us Web Forms for developing and running browser-based applications.

In event handling, the client really is a Web page. It has a title; it has got some of Web-enabled user interface devices, Web controls (textboxes and buttons). These controls are used to fire event against the machine that is serving the Web page. The user clicks a button, an event is fired, it goes through the Internet, and it arrives over at the Web server like IIS. IIS has a couple of code files (server scripts) that have been compiled. When the event fires, the event handler runs on the Web server. A Web page is dynamically created with the result, and that is sent back to the user. This is the model for Web Forms. 87. Write a note on Events. An event is a member that enables an object or class to provide notifications. A class defines an event by providing an event declaration and an optional set of event accessors. The declaration resembles a field declaration, though with an added event keyword. public delegate void EventHandler(object sender, System.EventArgs e); public class Button { public event EventHandler Click; public void Reset() {

P a g e | 41
Click = null; } } 88. What is Automatic garbage collection? / What is Garbage collection? Garbage collection in the Microsoft .NET common language runtime environment completely absolves the developer from tracking memory usage and knowing when to free memory. As we know Garbage Collector in .NET is in deterministic which means that we can never be sure when the garbage collector is invoked. We have destructors in C#. But unlike destructors in C++ which are automatically called when an object is in no longer in user, in C# destructors are nothing but finalize methods in disguise, with a call to base class's finalize method. As we know, finalize method is called during garbage collection by garbage collector. 89. Working of foreach looping statement. A foreach statement lets us iterate over the elements in arrays and collections. The elements of single dimensional arrays are traversed in increasing order of index, starting with index 0 to Length 1. The elements of multi-dimensional arrays elements are traversed such that the indices of the rightmost dimension are incremented first, then the next left dimension, and so on to the left. using System; class TestForeach { static void Main() { int[] array1 = new int[] {1,2,3,4,5}; foreach (int i in array1) Console.WriteLine(Value is ,0-, i); } } 90. JIT compiler. (Define JIT - compilation.) Microsoft's .NET Framework rely on JIT compilation for high-speed code execution. In computing, just-in-time compilation (JIT), also known as dynamic translation, is a technique for improving the runtime performance of a computer program. JIT builds upon two earlier ideas in run-time environments: bytecode compilation and dynamic compilation. It converts code at runtime prior to executing it natively, for example bytecode into native machine code. The performance improvement over interpreters originates from caching the results of translating blocks of code, and not simply reevaluating each line or operand each time it is met. 91. Abstract class. A class can indicate that it is incomplete, and is intended only as a base class for other classes, by including the modifier abstract. Such a class is called an abstract class. using System; abstract class A { public abstract void F(); } class B: A { public override void F() , Console.WriteLine(B.F); } class Test { static void Main() { B b = new B(); b.F(); A a = b; a.F(); } } The output will be

P a g e | 42
B.F B.F 92. Enums. (Explain the following with an example) An enum type declaration defines a type name for a related group of symbolic constants. Enums are used for multiple choice, in which a runtime decision is made from a fixed number of choices that are known at compile-time. enum Color { Red, Blue, Green } class Shape { public void Fill(Color color) { switch(color) { case:Color.Red: Console.WriteLine(RED); break; case:Color.Blue: Console.WriteLine(BLUE); break; case:Color.Green: Console.WriteLine(GREEN); break; default: break; } } } 93. Give the differences between web and web services? A web service is an application that we can call via browser in the same way that we call a web site, but web service normally is called by another application and send its answers in XML format. The one who made the request could read that XML file and work with that. 94. What is the use of lock statement? The lock statement obtains the mutual exclusion lock for a given object, executes statements, and then releases the lock. The example is shown below static void Main() { A a = ...; lock(a) { a.P = a.P + 1; } } 95. What is the use of using statement? The using statement obtains one or more resources, executes statements, and then releases of the resource. static void Main() { using (Resource r = new Resource()) { r.Func(); } }

Anda mungkin juga menyukai