You are on page 1of 8

Name- Ajay Kumar Dubey Reg.

No-511227403 Subject Code- MC0081

Course- MCA LC Code-03104 Subject Name-.(DOT) Net Technologies

Question:1. Describe the following with respect to creating Web Forms in .Net environment: a. Web Form Life Cycle b. Creating a Web Form Write programs with corresponding output screens to demonstrate the above concepts. Answer: Creating a Simple Windows Form :A Windows Form is a tool for building a Windows application. The .NET Framework offers extensive support for Windows application development, the centerpiece of which is the Windows Forms framework. Not surprisingly, Windows Forms use the metaphor of a form. This idea was borrowed from the wildly successful Visual Basic (VB) environment and supports Rapid Application Development (RAD). Arguably, C# is the first development environment to marry the RAD tools of Visual Basic with the object-oriented and high performance characteristics of a C-family language. Using Notepad :Visual Studio .NET provides a rich set of drag-and-drop tools for working with Windows Forms. It is possible to build a Windows application without using the Visual Studio Integrated Development Environment (IDE). Stage 1 Initialization : After the control hierarchy has been built, the Page, along with all of the controls in its control hierarchy, enter the initialization stage. This stage is marked by having the Page and controls fire their Init events. At this point in the page life cycle, the control hierarchy has been constructed, and the Web control properties that are specified in the declarative syntax have been assigned. Stage 2 - Load View State : The load view state stage only happens when the page has been posted back. During this stage, the view state data that had been saved from the previous page visit is loaded and recursively populated into the control hierarchy of the Page. It is during this stage that the view state is validated. As we'll discuss later in this article, the view state can become invalid due to a number of reasons, such as view state tampering, and injecting dynamic controls into the middle of the control hierarchy. Stage 3 - Load Postback Data : The load Postback data stage also only happens when the page has been posted back. A server control can indicate that it is interested in examining the posted back data by implementing the IPostBackDataHandler interface. In this stage in the page life cycle, the Page class enumerates the posted back form fields, and searches for the corresponding server control. If it finds the control, it checks to see if the control implements the IPostBackDataHandler interface. If it does, it hands off the appropriate postback data to the server control by calling the control's LoadPostData() method. The server control would then update its state based on this postback data. To help clarify things, let's look at a simple example. One nice thing about ASP.NET is that the Web controls in a Web Form remember their values across postback. That is, if you have a TextBox Web control on a page and the user enters some value into the TextBox and posts back the page, the TextBox's Text property is automatically updated to the user's entered value. This happens because the TextBox Web control implements the IPostBackDataHandler interface, and the Page class hands off the appropriate value to the TextBox class, which then updates its Text property. To concretize things, imagine that we have an ASP.NET Web page with a TextBox whose ID property is set to txtName. When the page is first visited, the following HTML will be rendered for the TextBox: <input type="text" id="txtName" name="txtName" />. When the user enters a value into this TextBox (such as, "Hello, World!") and submits the form, the browser will make a request to the same ASP.NET Web page, passing the form field values back in the HTTP POST headers. These include the hidden form field values (such as __VIEWSTATE), along with the value from the txtName TextBox. Stage 4 - Load : This is the stage with which all ASP.NET developers are familiar, as we've all created an event handler for a page's Load event (Page_Load). When the Load event fires, the view state has been loaded (from stage 2, Load View State), along with the postback data (from stage 3, Load Postback Data). Stage 5 - Raise Postback : Event Certain server controls raise events with respect to changes that occurred between postbacks. For example, the DropDownList Web control has a SelectedIndexChanged event, which fires if the DropDownList's SelectedIndex has changed from the SelectedIndex value in the previous page load. Another example: if the Web Form was posted back due to a Button Web control being clicked, the Button's Click event is fired during this stage. There are two flavors of postback events. The first is a changed event. This event fires when some piece of data is changed between postbacks. An example is the DropDownListsSelectedIndexChanged event, or the TextBox's TextChanged event. Server controls that provide changed events must implement the IPostBackDataHandler interface. The other flavor of postback events is the raised event. These are events that are raised by the server control for whatever reason the control sees fit. For example, the Button Web control raises the Click event when it is clicked, and the Calendar control raises the VisibleMonthChanged event when the user moves to another month. Controls that fire raised events must implement the IPostBackEventHandler interface. Stage 6 - Save View State : In the save view state stage, the Page class constructs the page's view state, which represents the state that must persist across postbacks. The page accomplishes this by recursively calling the SaveViewState() method of the controls in its control hierarchy. This combined, saved state is then serialized into a base-64 encoded string. In stage 7, when the page's Web Form is rendered, the view state is persisted in the page as a hidden form field. In the render stage the HTML that is emitted to the client requesting the page is generated. The Page class accomplishes this by recursively invoking the RenderControl() method of each of the controls in its hierarchy. These seven stages are the most important stages with respect to understanding view state. (Note that I did omit a couple of stages, such as the PreRender and Unload

stages.) As you continue through the article, keep in mind that every single time an ASP.NET Web page is requested, it proceeds through these series of stages. Creating a New ASP.NET Web Forms Page When you create a new Web site using the Studio adds an ASP.NET page (Web Forms page) named Default.aspx. You can use the Default.aspx page as the home page for your Web site. However, for this walkthrough, you will create and work with a new page. To add a page to the Web site 1. Close the Default.aspx page. To do this, name and then click Close 2. In Solution Explorer, right and then click Add New Item The Add New Item dialog box is displayed. The following illustration shows an example of the Add New Item 3. In the template list, select 4. In the Name box, type programming language for that page or component. You can use different Programming languages in the same Web site. 5. Clear the Place code in separate file ASP.NET Web Site project template, Visual right-click the tab that displays the file close. , right-click the Web site (for example, C:\BasicWebSite),Item. dialog box. Web Form. First Webpage. When you created the Web site project, you specified a default language based on the project template that you selected. However, each time a new page or component for your Web site, you can select the check box. You create In this walkthrough, you are creating a single-file page with the code and HTML in the same page. The code for ASP.NET pages can be located either in the page or in a separate class file. 6. Click Add. Visual Studio creates the new page and opens it. Adding HTML to the Page In this part of the walkthrough, you will add some static text to the page. To add text to the page 1. At the bottom of the document window, click the Design tab to switch to Design view. Design view displays the page that you are working on in a WYSIWYG-like way. At this point, you do not have any text or controls on the page, so the page is blank except for a dashed line that outlines a rectangle. This rectangle represents a div element on the page. 2. Click inside the rectangle that is outlined by a dashed line. 3. Type Welcome to Visual Web Developer and press ENTER twice. The following illustration shows the text you typed in Design view. 4. Switch to Source view. You can see the HTML that you created by typing in Design view, as shown in the following illustration. Question: 2. Describe the following with respect to State Management in ASP.Net: a. Cookies in ASP.NET b. Session State c. Application State Answer : a. Cookies in asp.net : Web applications can store small pieces of data in the clients Web browser by using cookies. A cookie is a small amount of data that is stored either in a text file on the client file system (if the cookie is persistent) or in memory in the client browser session (if the cookie is temporary). The most common use of cookies is to identify a single user as he or she visits multiple Web pages. Reading and Writing Cookies: A Web application creates a cookie by sending it to the client as a header in an HTTP response. The Web browser then submits the same cookie to the server with every new request. Create a cookie -> add a value to the Response. Cookies HttpCookieCollection. Read a cookie -> read values in Request. Cookies. Example: // Check if cookie exists, and display it if it does if (Request.Cookies["lastVisit"] != null) // Encode the cookie in case the cookie contains clientside script Label1.Text = Server.HtmlEncode(Request.Cookies["lastVisit"].Value); else Label1.Text = "No value defined"; // Define the cookie for the next visit Response.Cookies["lastVisit"].Value = DateTime.Now.ToString();Response.Cookies["lastVisit"].Expires = DateTime.Now.AddDays(1); If you do not define the Expires property, the browser stores it in memory and the cookie is lost if the user closes his or her browser. To delete a cookie, overwrite the cookie and set an expiration date in the past. You cant directly delete cookies because they are stored on the clients computer. Controlling the Cookie Scope: By default, browsers wont send a cookie to a Web site with a different hostname. You can control a cookies scope to either limit the scope to a specific folder on the Web server or expand the scope to any server in a domain. To limit the scope of a cookie to a folder, set the Path property, as the following example demonstrates: Example: Response.Cookies["lastVisit"].Path = "/Application1"; Through this the scope is limited to the /Application1 folder that is the browser submits the cookie to any page with in this folder and not to pages in other folders even if the folder is in the same server. We can expand the scope to a particular domain using the following statement: Example: Response.Cookies[lastVisit].Domain = Contoso; Storing Multiple Values in a Cookie: Though it depends on the browser, you typically cant store more than 20 cookies per site, and each cookie can be a maximum of 4 KB in length. To work around the 20-cookie limit, you can store multiple values in a cookie, as the following code demonstrates:

Example: Response.Cookies["info"]["visit"].Value = DateTime.Now.ToString(); Response.Cookies["info"]["firstName"].Value = "Tony"; Response.Cookies["info"]["border"].Value = "blue"; Response.Cookies["info"].Expires = DateTime.Now.AddDays(1); Running the code in this example sends a cookie with the following value to the Web browser: (visit=4/5/2006 2:35:18 PM) (firstName=Tony) (border=blue) Query Strings: Query strings are commonly used to store variables that identify specific pages, such as search terms or page numbers. A query string is information that is appended to the end of a page URL. A typical query string might look like the following real-world example: http://support.microsoft.com/Default.aspx?kbid=315233 In this example, the URL identifies the Default.aspx page. The query string (which starts with a question mark [?]) contains a single parameter named kbid, and a value for that parameter, 315233. Query strings can also have multiple parameters, such as the following real-world URL, which specifies a language and query when searching the Microsoft.com Web site: http://search.microsoft.com/results.aspx? mkt=en-US&setlang=en-US&q=hello+world Value Name | ASP.NET Object | Value mkt | Request.QueryString[mkt] | en-US setlang | Request.QueryString[setlang] | en-US q | Request.QueryString[q] | hello world Limitations for Query Strings: 1. Some Browsers and client devices impose a 2083 character limit on the length of the URL. 2. You must submit the page using an HTTP GET command in order for query string values to be available during page processing. Therefore, you shouldnt add query strings to button targets in forms. 3. You must manually add query string values to every hyperlink that the user might click. Example: Label1.Text = "User: " + Server.HtmlEncode(Request.QueryString["user"]) + ", Prefs: " + Server.HtmlEncode(Request.QueryString["prefs"]) + ", Page: " + Server.HtmlEncode(Request.QueryString["page"]); Server - Side State Management: B. Session State: ASP.NET allows you to save values using session state, a storage mechanism that is accessible from all pages requested by a single Web browser session. Therefore, you can use session state to store user-specific information. Session state is similar to application state, except that it is scoped to the current browser session. If different users are using your application, each user session has a different session state. In addition, if a user leaves your application and then returns later after the session timeout period, session state information is lost and a new session is created for the user. Session state is stored in the Session key/value dictionary. You can use session state to accomplish the following tasks: i. Uniquely identify browser or client-device requests and map them to individual session instances on the server. This allows you to track which pages a user saw on your site during a specific visit. ii. Store session-specific data on the server for use across multiple browser or client-device requests during the same session. This is perfect for storing shopping cart information. iii. Raise appropriate session management events. In addition, you can write application code leveraging these events. ASP.NET session state supports several different storage options for session data: a. InProc Stores session state in memory on the Web server. This is the default, and it offers much better performance than using the ASP.NET state service or storing state information in a database server. InProc is fine for simple applications, but robust applications that use multiple Web servers or must persist session data between application restarts should use State Server or SQLServer. b. StateServer Stores session state in a service called the ASP.NET State Service. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm. ASP.NET State Service is included with any computer set up to run ASP.NET Web applications; however, the service is set up to start manually by default. Therefore, when configuring the ASP.NET State Service, you must set the startup type to Automatic. c. SQLServer Stores session state in a SQL Server database. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm. On the same hardware, the ASP.NET State Service outperforms SQLServer. However, a SQL Server database offers more robust data integrity and reporting capabilities. d. Custom Enables you to specify a custom storage provider. You also need to implement the custom storage provider. e. Off Disables session state. You should disable session state if you are not using it to improve performance. C.Application State: ASP.NET allows you to save values using application state, a global storage mechanism that is accessible from all pages in the Web application. Application state is stored in the Application key/value dictionary. Once you add your application-specific information to application state, the server manages it, and it is never exposed to the client. Application state is a great place to store information that is not user-specific. By storing it in the application state, all pages can access data from a single location in memory, rather than keeping separate copies of the data. Data stored in the Application object is not permanent and is lost any time the application is restarted. ASP.NET provides three events that enable you to initialize Application variables (free resources when the application shuts down) and respond to Application errors:

a. Application_Start: Raised when the application starts. This is the perfect place to initialize Application variables. b. Application_End: Raised when an application shuts down. Use this to free application resources and perform logging. c. Application_Error: Raised when an unhandled error occurs. Use this to perform error logging. Question : 3. Describe the following with respect to Web Services in .Net: a. Writing and Testing a Web Service b. Implementing a Web Service Client Answer : A. Testing A Web Service How do you test an ASMX Web service? Simple: just call it in your browser. To demonstrate, copy Calc.asmx to wwwroot and type http://localhost/calc.asmx in your browsers address bar. Youll be greeted with the screen shown in Figure 8.6. What happened? ASP.NET responded to the HTTP request for Calc.asmx by generating an HTML page that describes the Web service. The name and description in the ASMX files WebService attribute appear at the top of the page. Underneath is a list of Web methods that the service exposes, complete with the descriptions spelled out in the WebMethod attributes.

Click Add near the top of the page, and ASP.NET displays a page that you can use to test the Add method (Figure 8.7). ASP.NET knows the method name and signature because it reads them from the metadata in the DLL it compiled from Calc.asmx. It even generates an HTML form that you can use to call the Add method with your choice of inputs. Type 2 and 2 into the a and b boxes and click Invoke. The XML returned by the Web method appears in a separate browser window The forms that ASP.NET generates on the fly from ASMX files enable you to test the Web services that you write without writing special clients to test them with. They also let you explore a Web service built with the .NET Framework simply by pointing your browser to it. For kicks, type the following URL into your browsers address bar: http://terraservice.net/terraservice.asmx Thats the URL of the Microsoft Terra Service, an ultra-cool Web service that provides a programmatic interface to a massive database of geographic data known as the Microsoft TerraServer. Dont worry about the details just yet; youll be using Terra Service to build a Web service client later in this chapter. But do notice how much you can learn about Terra Service simply by viewing the page that ASP.NET generated for it. Answer : B .Testing A Web Service Implementing Web Service Clients Now that youve seen Web services up close and personal, its time to learn about Web service clients that is, applications that use, or consume, Web methods. Its easy to write Web services. Writing Web service clients is even easier, thanks to some high-level support lent by the .NET Framework class library (FCL) and a codegenerator named Wsdl.exe. If you have a WSDL contract describing a Web service (or the URL of a DISCO file that). Question 4. Describe the following with respect to Web site deployment in ASP.Net: a. Creating Application Pools (IIS 6.0) b. Deploying ASP.NET Applications Answer : a. Creating Application Pools (IIS 6.0) When you run IIS 6.0 in worker process isolation mode, you can isolate different Web applications or Web sites in pools, which are called Application Pools. An application pool is a group of URLs that are routed to one or more worker processes that share the same configuration. The URLs that you assign to an application pool can be for an application, a Web site, a Web directory, or a virtual directory. In an application pool, process boundaries separate each worker process from other worker processes so that when an application is routed to one application pool, applications in other application pools do not affect that application. By using an application pool, you can assign specific configuration settings to a worker process (or, in the case of a Web garden, to a set of worker processes) that services a group of applications. For example, you can configure worker process recycling, which offers several configuration options to match the needs of each application. If, for example, you suspect that an application has a memory leak, you might configure the application pools worker process to recycle when its memory use reaches a certain threshold. If another application fails because of the volume of requests that it receives, you can set the application pools worker process to recycle when the application exceeds a specified number of requests. By creating new application pools and assigning Web sites and applications to them, you can make your server

more efficient, reliable, and secure, and ensure that your applications remain available even when a worker process serving an application pool is recycled because of a faulty application. Guidelines for Creating Application Pools: To isolate Web applications on a Web site from Web applications on other sites running on the same computer, create an individual application pool for each Web site. For enhanced security, configure a unique user account (process identity) for each application pool. Use an account with the least user rights possible, such as Network Service in the IIS_WPG group. If there is a test version of an application on the same server with the production version of the application, separate the two versions into different application pools. This isolates the test version of the application. As a design consideration, if you want to configure an application to run with its own unique set of properties, create a unique application pool for that application. Note: You must be a member of the Administrators group on the local computer to perform the following procedure or procedures. As a security best practice, log on to your computer by using an account that is not in the Administrators group, and then use the runas command to run IIS Manager as an administrator. At a command prompt, type runas /user:Administrative_AccountName "mmc %systemroot%\system32\inetsrv\iis.msc". Steps to create a new Application Pool: 1. In IIS Manager, expand the local computer, right-click Application Pools, point to New, and then click Application Pool. 2. In the Application pool name box, type the name of the new application pool. 3. If the ID that appears in Application pool ID box is not the ID that you want, type a new ID. 4. Under Application pool settings, click the appropriate setting. If you click Use existing application pool as template, in Application pool name box, right-click the application pool that you want to use as a template. 5. Click OK. Application pools allow you to apply configuration settings to groups of applications and the worker processes that service those applications. Any Web site, Web directory, or virtual directory can be assigned to an application pool. B .Deploying ASP.NET Applications in IIS 6.0 (IIS 6.0) Microsoft Windows Server 2003 includes support for ASP.NET applications and the Microsoft .NET Framework version 1.1 with the operating system installation. This chapter describes how to deploy ASP.NET applications on a newly installed server running Internet Information Services (IIS) 6.0. Version 1.1 of the .NET Framework is installed with Windows Server 2003. Most ASP.NET applications run without modification on version 1.1 of the .NET Framework. Overview of Deployment process using IIS 6.0 : ASP.NET is a unified Web application platform that provides services to help you build and deploy enterprise-class Web applications and XML-based Web services. ASP.NET is supported on the Microsoft Windows Server 2003, Standard Edition; Windows Server2003, Enterprise Edition; Windows Server2003, Datacenter Edition; and Windows Server2003, Web Edition operating systems. ASP.NET is installed with the Microsoft .NET Framework version 1.1 as a part of Windows Server 2003. However, to run ASP.NET applications, you must also install IIS 6.0. ASP.NET is not available on the following operating systems: Microsoft Windows XP 64-Bit Edition; the 64-bit version of Windows Server 2003, Enterprise Edition; and the 64-bit version of Windows Server 2003, Datacenter Edition. The deployment process presented in this section describes how to deploy ASP.NET applications on a newly installed IIS 6.0 Web server. Before you begin this process, complete the following steps: Install Windows Server 2003, which includes version 1.1 of the .NET Framework, with the default options. Install IIS 6.0 with the default settings in Add or Remove Programs in Control Panel. When you configure IIS 6.0 to run in IIS 5.0 isolation mode, the settings in the <processModel> section of the Machine.config file are configured in the same way as they were in IIS 5.0 in the Machine.config or Web.config files. Upon completing the process described in this section, you will have a Web server running IIS 6.0 and hosting your ASP.NET applications. However, you can further configure the Web server to improve the security and availability of your ASP.NET applications. Deployment Process using IIS 6.0 : The process for deploying new ASP.NET applications on a newly installed Web server requires no understanding of earlier versions of IIS or the .NET Framework. All the ASP.NET configuration sections in the Machine.config and Web.config files are configured the same way in IIS 6.0, except for the <processModel> section of the Machine.config file. When IIS 6.0 is configured to run in worker process isolation mode, some of the attributes in the <processModel> section of the Machine.config file are now in equivalent IIS 6.0 metabase properties. In addition, if your ASP.NET applications need to retain session state, you must configure IIS 6.0 to use the appropriate ASP.NET application session state method. Depending on the method you select, you might need to configure the ASP.NET state service or Microsoft SQL Server to act as the repository for centralized state storage. The process for deploying ASP.NET applications in IIS 6.0 is shown in Figure

Deploying ASP.NET Applications in IIS 6.0

Note: Before deploying your ASP.NET applications on a production server, perform the process outlined in this section on a test server that is configured identically to your production server. Deploy the Web Server 1. Install Windows Server 2003. 2. Install and configure IIS 6.0. 3. Enable ASP.NET in the Web service extensions list. Install ASP.NET Applications : 1. Create Web sites and virtual directories for each ASP.NET application by doing the following: Create Web sites and home directories. Create virtual directories. 2. Copy ASP.NET application content to the Web server. 3. Enable common storage for ASP.NET session state by completing the following steps: Step-1: Select the method for maintaining and storing ASP.NET session state. Step-2: If you have decided to maintain session state with the ASP.NET state service, configure out-of-process session state with the ASP.NET state service. Step-3: If you have decided to maintain session state with SQL Server, configure out-of-process session state with SQL Server. Step-4: Configure encryption and validation keys. Step-5: Configure ASP.NET to use the appropriate session state. Step-6: Secure the ASP.NET session state connection string. Complete the ASP.NET Application Deployment Practical Questions Question:5. Write a program in C# language to perform the following operations: a. Basic arithmetic operations b. Finding greatest of n numbers Write separate programs for each of the above points. Answer: a. Basic arithmetic operations :Source Code: using System; using System.Collections.Generic; using System.Text; namespace SwitchCase { class SwitchCaseExample { static bool ReadInteger(out int n) { string input = System.Console.ReadLine(); n = 0; try { n = Convert.ToInt32(input); return true; } catch (System.Exception ex) { System.Console.WriteLine("Error in the input format\n\n"); return false; } } static void Main(string[] args) { int a, b, opcode, result; System.Console.WriteLine("Program for Addition, Subtraction, Multiplication and Division\n"); while (true) { System.Console.Write("Enter Your Choice: 1 - Add, 2 - Sub, 3 - Mul, 4 - Div: "); ReadInteger(out opcode); if (opcode < 1 || opcode > 4) return; System.Console.Write("Enter First Number:"); ReadInteger(out a); System.Console.Write("Enter Second Number:"); ReadInteger(out b); switch (opcode) { case 1: result = a + b; System.Console.WriteLine("{0} + {1} = {2}", a, b, result); break; case 2: result = a - b;

System.Console.WriteLine("{0} - {1} = {2}", a, b, result); break; case 3: result = a * b; System.Console.WriteLine("{0} * {1} = {2}", a, b, result); break; case 4: result = a / b; System.Console.WriteLine("{0} / {1} = {2}\n{3} % {4} = {5}", a, b, result, a, b, a % b); break; default: break; } } } } } Output Program for Addition,Subtraction,Multiplication and Division Enter your choice: 1 Add, 2- Sub, 3 Mul, 4 Div: 1 Enter First Number :34 Enter Second Number:45 34+45=79 Enter your choice: 1 Add, 2- Sub, 3 Mul, 4 Div: 2 Enter First Number :34 Enter Second Number:22 34-22=12 Enter your choice: 1 Add, 2- Sub, 3 Mul, 4 Div: 3 Enter First Number :45 Enter Second Number:4 45*4=180 Enter your choice: 1 Add, 2- Sub, 3 Mul, 4 Div: 4 Enter First Number :22 Enter Second Number:2 22/2=11 22%2=0 Enter your choice: 1 Add, 2- Sub, 3 Mul, 4 Div: b. Finding greatest of n numbers using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication23 { class Program { static void Main(string[] args) { int i, largest; int[] array = new int[5]; for (i = 0; i < 5; i++) { Console.WriteLine("Enter elements:{0}", i+1); array[i] = Convert.ToInt32(Console.ReadLine()); } largest = array[0]; for (i = 0; i <5; i++) { if (array[i] > largest) { largest = array[i]; }} Console.WriteLine("The Largest number is :{0}", largest); Console.ReadLine(); }} } Output : Enter Elements: 1 50 Enter Elements: 2 60 Enter Elements: 3 41 Enter Elements: 4 22 Enter Elements: 5 11 The Largest number is : 60

Question: 6. Describe the steps involved in creating classes and objects with the help of a program in C#. Answer: A class is a construct that enables you to create your own custom types by grouping together variables of other types, methods and events. A class is like a blueprint. It defines the data and behavior of a type. If the class is not declared as static, client code can use it by creating objects or instances which are assigned to a variable. The variable remains in memory until all references to it go out of scope. At that time, the CLR marks it as eligible for garbage collection. If the class is declared as static, then only one copy exists in memory and client code can only access it through the class itself, not an instance variable. For more information, see Static Classes and Static Class Members (C# Programming Guide).Unlike structs, classes support inheritance, a fundamental characteristic of object-oriented programming. Declaring classes Declaring classes public class Customer { //Fields, properties, methods and events go here... } Creating object Customer object1 = new Customer(); Class Inheritance public class Manager : Employee { // Employee fields, properties, methods and events are inherited // New Manager fields, properties, methods and events go here... } EXAMPLE public class Person { // Field public string name; // Constructor public Person() { name = "unknown"; } // Method public void SetName(string newName) { name = newName; } } class TestPerson { static void Main() { Person person = new Person(); Console.WriteLine(person.name); person.SetName("John Smith"); Console.WriteLine(person.name); // Keep the console window open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); } } /* Output: unknown John Smith */ { name = "unknown"; } // Method

You might also like