You are on page 1of 10

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. a) WEB FORM LIFE CYCLE Every request for a page made from a web server causes a chain of events at the server. These events, from beginning to end, constitute the life cycle of the page and all its components. The life cycle begins with a request for the page, which causes the server to load it. When the request is complete, the page is unloaded. From one end of the life cycle to the other, the goal is to render appropriate HTML output back to the requesting browser. The life cycle of a page is marked by the following events, each of which you can handle yourself or leave to default handling by the ASP.NET server: Initialize: Initialize is the first phase in the life cycle for any page or control. It is here that any settings needed for the duration of the incoming request are initialized. Load View State: The View State property of the control is populated. The View State information comes from a hidden variable on the control, used to persist the state across round trips to the server. The input string from this hidden variable is parsed by the page framework, and the View State property is set. This can be modified via the LoadViewState ( ) method: This allows ASP.NET to manage the state of your control across page loads. So that each control is not reset to its default state each time the page is posted. Process Postback Data: During this phase, the data sent to the server in the posting is processed. If any of this data results in a requirement to update the View State, that update is performed via the LoadPostData ( ) method. Load: CreateChildControls ( ) is called, if necessary, to create and initialize server controls in the control tree. State is restored, and the form controls show client-side data. You can modify the load phase by handling the Load event with the OnLoad method. Send Postback Change Modifications: If there are any state changes between the current state and the previous state, change events are raised via the RaisePostDataChangedEvent ( ) method. Handle Postback Events: The client-side event that caused the postback is handled. PreRender: This is the phase just before the output is rendered to the browser. It is essentially your last chance to modify the output prior to rendering using the OnPreRender ( ) method. Save State: Near the beginning of the life cycle, the persisted view state was loaded from the hidden variable. Now it is saved back to the hidden variable, persisting as a string object that will complete the round trip to the client. You can override this using the SaveViewState () method. Render: This is where the output to be sent back to the client browser is generated. You can override it using the Render method. CreateChildControls ( ) is called, if necessary, to create and initialize server controls in the control tree. Dispose: This is the last phase of the life cycle. It gives you an opportunity to do any final cleanup and release references to any expensive resources, such as database connections. You can modify it using the Dispose ( ) method. b) CREATING A WEB FORM To create the simple Web Form that will be used in the above example, go to the option start up Visual Studio .NET and open a New Project named ProgrammingCSharpWeb. Select the Visual C# Projects folder (because C# is your language of choice), select ASP.NET Web Application as the project type, and type in its name, ProgrammingCSharpWeb. Visual Studio places nearly all the files it creates for the project in a folder within your local machine's default web site for example, c:\Inetpub\wwwroot\ProgrammingCSharpWeb. The solution files and other Visual Studio-specific files are stored in <drive>\Documents and Settings\<user name>\My Documents\Visual Studio Projects (where <drive>and <user name>are specific to your machine). When the application is created, Visual Studio places a number of files in your project. The Web Form itself is stored in a file named WebForm1.aspx. This file will contain only HTML. A second, equally important file, WebForm1.aspx.cs, stores the C# associated with your form; this is the code-behind file. The code-behind file does not appear in the Solution Explorer. To see the code behind (.cs) file, you must place the cursor within Visual Studio .NET, right-click the form, and choose "View Code" in the pop-up menu. You can now tab back and forth between the forms itself, WebForm1.aspx, and the C# code-behind file, WebForm1.aspx.cs. When viewing the form, WebForm1.aspx, you can choose between Design mode and HTML mode by clicking the tabs at the bottom of the Editor window. Design mode lets you drag controls onto your form; HTML mode allows you to view and edit the HTML code directly. code-behind files: Start by renaming WebForm1.aspx to HelloWeb.aspx. To do this, close WebForm1.aspx,and then right-click its name in the Solution Explorer. Choose Rename and enter the name HelloWeb.aspx. After renaming it, open HelloWeb.aspx and view the code; it is seen that code-behind file has been renamed as well to HelloWeb.aspx.cs.When you create a new Web Form application, Visual Studio .NET will generate a bit of boilerplate code to get you started, as shown below: <%@ Page language="c#" Codebehind="HelloWeb.aspx.cs" AutoEventWireup="false" Inherits="ProgrammingCSharpWeb.WebForm1" %>

<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <html> <head> <title>WebForm1</title> <meta name="GENERATOR" Content="Microsoft Visual Studio 7.0"> <meta name="CODE_LANGUAGE" Content="C#"> <meta name="vs_defaultClientScript" content="JavaScript"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5"> </head> <body MS_POSITIONING="GridLayout"> <form id="Form1" method="post" runat="server"> </form> </body> </html> Run the page by pressing Ctrl-F5 (or save it and navigate to it in your browser). 2. Describe the following with respect to State Management in ASP.Net: a. Cookies in ASP.NET b. Session State c. Application State a)COOKIES IN ASP.NET Introduction: Cookies provide a means in Web applications to store user-specific information. For example, when a user visits your site, you can use cookies to store user preferences or other information. When the user visits your Web site another time, the application can retrieve the information it stored earlier. A cookie is a small bit of text that accompanies requests and pages as they go between the Web server and browser. The cookie contains information the Web application can read whenever the user visits the site. Cookies are associated with a Web site, not with a specific page, so the browser and server will exchange cookie information no matter what page the user requests from your site. As the user visits different sites, each site might send a cookie to the user's browser as well; the browser stores all the cookies separately. Cookies help Web sites store information about visitors. Generally, cookies are one way of maintaining continuity in a Web applicationthat is, of performing state management. Except for the brief time when they are actually exchanging information, the browser and Web server are disconnected. Each request a user makes to a Web server is treated independently of any other request. Many times, however, it's useful for the Web server to recognize users when they request a page. For example, the Web server on a shopping site keeps track of individual shoppers so the site can manage shopping carts and other user-specific information. A cookie therefore acts as a kind of calling card, presenting pertinent identification that helps an application know how to proceed. Cookies are used for many purposes, all relating to helping the Web site remember users. For example, a site conducting a poll might use a cookie simply as a Boolean value to indicate whether a user's browser has already participated in voting so that the user cannot vote twice. A site that asks a user to log on might use a cookie to record that the user already logged on so that the user does not have to keep entering credentials. Cookie Limitations: Most browsers support cookies of up to 4096 bytes. Because of this small limit, cookies are best used to store small amounts of data, or better yet, an identifier such as a user ID. Browsers also impose limitations on how many cookies your site can store on the user's computer. Most browsers allow only 20 cookies per site; if you try to store more, the oldest cookies are discarded. Some browsers also put an absolute limit, usually 300, on the number of cookies they will accept from all sites combined. Users can set their browser to refuse cookies. If you define a P3P privacy policy and place it in the root of your Web site, more browsers will accept cookies from your site. However, you might have to avoid cookies altogether and use a different mechanism to store user-specific information. A common method for storing user information is session state, but session state depends on cookies, as explained later in the section "Cookies and Session State."

Writing Cookies

The browser is responsible for managing cookies on a user system. Cookies are sent to the browser via the HttpResponse object that exposes a collection called cookies. You can access the HttpResponse object as the Response property of your Page class. Any cookies that you want to send to the browser must be added to this collection. When creating a cookie, you specify a Name and Value. Each cookie must have a unique name so that it can be identified later when reading it from the browser. Because cookies are stored by name, naming two cookies the same will cause one to be overwritten. If you do not set the cookie's expiration, the cookie is created but it is not stored on the user's hard disk. Instead, the cookie is maintained as part of the user's session information. When the user closes the browser, the cookie is discarded. You can add cookies to the Cookies collection in a number of ways. The following example shows the method using C# code to write cookies: Response.Cookies ["userName"].Value = "patrick"; Response.Cookies ["userName"].Expires = DateTime.Now.AddDays (1); HttpCookieaCookie = new HttpCookie ("lastVisit"); aCookie.Value = DateTime.Now.ToString (); aCookie.Expires = DateTime.Now.AddDays (1); Response.Cookies.Add (aCookie); b) SESSION STATEASP.NET session state enables you to store and retrieve values for a user as the user navigates the different ASP.NET pages that make up a Web application. HTTP is a stateless protocol, meaning that your Web server treats each HTTP request for a page as an independent request; by default, the server retains no knowledge of variable values used during previous requests. As a result, building Web applications that need to maintain some cross-request state information (applications that implement shopping carts, data scrolling, and so on) can be a challenge. ASP.NET session state identifies requests received from the same browser during a limited period of time as a session, and provides the ability to persist variable values for the duration of that session. ASP.NET session state is enabled by default for all ASP.NET applications. ASP.NET session-state variables are easily set and retrieved using the Session property, which stores session variable values as a collection indexed by name.to be ASP.NET stores session information in the memory space of the ASP.NET application by default. We can optionally, store session information using a stand-alone service so that session information is preserved if the ASP.NET application is restarted, in a SQL Server so that session information is available to multiple Web servers in a Web farm (and also persists if the ASP.NET application is restarted), or in a custom data store. ASP.NET also provides several other options for persisting data within an application besides session state. Session Variables: Session variables are stored in a SessionStateItemCollection object that is exposed through the HttpContext: Session property. In an ASP.NET page, the current session variables are exposed through the Session property of the Page object. The collection of session variables is indexed by the name of the variable or by an integer index. Session variables are created by referring to the session variable by name. You do not have to declare a session variable or explicitly add it to the collection. The following example shows how to create session variables in an ASP.NET page for the first and last name of a user, and set them to values retrieved from TextBox controls. Session variables can be any valid .NET Framework type. Session Identifiers:Sessions are identified by a unique identifier that can be read by using the SessionID property. When session state is enabled for an ASP.NET application, each request for a page in the application is examined for a SessionID value sent from the browser. If no SessionID value is supplied, ASP.NET starts a new session and the SessionID value for that session is sent to the browser with the response. By default, SessionID values are stored in a cookie. However, you can also configure the application to store SessionID values in the URL for a "cookieless" session. A session is considered active as long as requests continue made with the same SessionID value. If the time between requests for a particular session exceeds the specified time-out value in minutes, the session is considered expired. Requests made with an expired SessionID value result in a new session. Session Modes:ASP.NET session state supports several storage options for session variables. Each option is identified as a session-state Mode type. The default behavior is to store session variables in the memory space of the ASP.NET worker process. However, you can also specify that session state should be stored in a separate process, in a SQL Server database, or in a custom data source. If you do not want session state enabled for your application, you can set the session mode to Off. Session Events:

ASP.NET provides two events that help you manage user sessions. The Session_OnStart event is raised when a new session starts, and the Session_OnEnd event is raised when a session is abandoned or expires. Session events are specified in the Global.asax file for an ASP.NET application. The Session_OnEnd event is not supported if the session Mode property is set to a value other than InProc, which is the default mode. Configuring Session State Session state is configured by using the sessionState element of the system.web configuration section. You can also configure session state by using the EnableSessionState value in the @ Page directive. The sessionStateelement enables you to specify the following options: The mode in which the session will store data. The way in which session identifier values are sent between the client and the server. The session Timeout value. Supporting values that are based on the session Mode setting.

The following example shows a sessionState element that configures an application for SQLServer session mode. It sets the Timeout value to 30 minutes, and specifies that session identifiers are stored in the URL. <sessionState mode="SQLServer" cookieless="true regenerateExpiredSessionId="true " timeout="30" SqlConnectionString="Data Source=MySqlServer;Integrated Security=SSPI;" stateNetworkTimeout="30"/> We can disable session state for an application by setting the session-state mode to off. c)APPLICATION STATE Application state is a data repository available to all classes in an ASP.NET application. Application state is stored in memory on the server and is faster than storing and retrieving information in a database. Unlike session state, which is specific to a single user session, application state applies to all users and all sessions. Therefore, application state is a useful place to store small amounts of often-used data that does not change from one user to another. Using Application State: Application state is stored in an instance of the HttpApplicationState class. This class exposes a key-value dictionary of objects. The HttpApplicationState instance is created the first time a user accesses any URL resource in an application. The HttpApplicationState class is most often accessed through the Application property of the HttpContext class. Application can be used in two ways: We can add, access, or remove values from the Contents collection directly through code. The HttpApplicationState class can be accessed at any time during the life of an application. Alternatively, we can add objects to the StaticObjects collection via an <object runat="server"> declaration in your Web application's Global.asax file. Application state defined in this way can then be accessed from code anywhere in your application. Application State Considerations: When using application state, you must be aware of the following important considerations: Resources: Because it is stored in memory, application state is very fast compared to saving data to disk or a database. However, storing large blocks of data in application state can fill up server memory, causing the server to page memory to disk. As an alternative to using application state, you can use the ASP.NET cache mechanism for storing large amounts of application data. The ASP.NET cache also stores data in memory and is therefore very fast; however, ASP.NET actively manages the cache and will remove items when memory becomes scarce. Volatility: As the application state is stored in server memory, it is lost whenever the application is stopped or restarted. For example, if the Web.config file is changed, the application is restarted and all application state is lost unless application state values have been written to a non-volatile storage medium such as a database. Scalability: Application state is not shared among multiple servers serving the same application, as in a Web farm, or among multiple worker processes serving the same application on the same server, as in a Web garden. Your application therefore cannot rely on application state containing the same data for application state across different servers or processes. If your application runs in multi-processor or multi-server environments, consider using a more scalable option, such as a database, for data that must preserve fidelity across the application. Concurrency: Application state is free-threaded, which means that application state data can be accessed simultaneously by many threads. Therefore, it is important to ensure that when you update application state data, you do so in a thread-safe manner by including built-in synchronization support. You can use the Lock and UnLock methods to ensure data integrity by locking the data for writing by only one source at a time. 3. Describe the following with respect to Web Services in .Net: a. Writing and Testing a Web Service b. Implementing a Web Service Client

a) WRITING AND TESTING A WEB SERVICE b) Writing a Web Service: The ASMX file shown in Figure below. It implements two Web methods: Add and Subtract. Both take two integers as input and return an integer as well. Deploying the Web service is as simple as copying it to a directory on your Web server that is URLaddressable. If you put Calc.asmx in wwwroot, the Web services local URL is http://localhost/calc.asmx. Calc.asmx demonstrates several important principles of Web service programming using the .NET Framework: Web services are implemented in ASMX files. ASMX is a special file name extension registered to ASP.NET (specifically, to an ASP.NET HTTP handler) in Machine.config. ASMX files begin with @ WebService directives. At a minimum, the directive must contain a Class attribute identifying the class that makes up the Web service. Web service classes can be attributed with optional WebService attributes. The one in this example assigns the Web service a name and a description that show up in the HTML page generated when a user calls up Calc.asmx in his or her browser. The WebService attribute also supports a Namespace parameter that can be used to change the name of the XML namespace that scopes the Web services members. Web methods are declared by tagging public methods in the Web service class with WebMethod attributes. You can build helper methods into a Web service methods that are used internally by Web methods but that are not exposed as Web methods themselves by omitting the attribute. The WebMethod attributes in Figure 8.5 also assign descriptive text to their Web methods. Youll learn more about Description and other WebMethod parameters in the section entitled The WebMethod AttributeTesting a Web Service:

For testing an ASMX Web service, call it in the browser. Copy Calc.asmx to wwwroot and type http://localhost/calc.asmxin the browsers address bar. User will be greeted as shown in the figure. 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 TerraService, an ultra-cool Web service that provides a programmatic interface to a massive database of geographic data known as the Microsoft TerraServer. c) IMPLEMENTING A WEB SERVICE CLIENTS:

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 points to a WSDL contract). Web Service Proxies: The key concept to grasp when writing Web service clients is that of the Web service proxy. A Web service proxy is an object that provides a local representation of a remote Web service. A proxy is instantiated in the clients own application domain, but calls to the proxy flow through the proxy and out to the Web service that the proxy represents. The Wsdl.exe utility that comes with the .NET Framework SDK (and that is integrated into Visual Studio .NET) generates Web service proxy classes from WSDL contracts. The methods in the proxy class mirror the Web methods in the Web service. If the Web service exposes Web methods named Add and Subtract, the Web service proxy also contains methods named Add and Subtract. When you call one of these methods, the proxy packages up the input parameters and invokes the Web method using the protocol encapsulated in the proxy (typically SOAP). The proxy insulates you from the low-level details of the Web service and of the protocols that it uses. It even parses the XML that comes back and makes the result available as managed types.

Simple Web Service Client:To write a client, following are the steps: Use Wsdl.exe to create a proxy class for Calc.asmx. If you installed Calc.asmx in wwwroot, the proper command is wsdl http://localhost/calc.asmx Wsdl.exe responds by creating a file named Calculator Web Service.cs. Create a new text file named CalcClient.cs and enter the code in Figure. Compile the CS files into a console application with the following command: cscCalcClient.cs "Calculator Web Service.cs" Run CalcClient.exe.

CalcClient.exe instantiates a Web service proxy and calls the services Add method. The resulting output proves beyond the shadow of a doubt that Calc.asmx is smart enough to add 2 and 2 CalcClient.cs using System; classMyApp { public static void Main () { CalculatorWebServicecalc = new CalculatorWebService (); int sum = calc.Add (2, 2); Console.WriteLine ("2 + 2 = " + sum); } } Avoiding Hard-Coded Service URLs: Look through a CS file generated by Wsdl.exe, and youll see the Web service proxy class as well as the methods that wrap the Web services Web methods. Youll also see that the Web services URL is hardcoded into the CS file in the proxys class constructor. Eg: publicCalculatorWebService() { this.Url = "http://www.wintellect.com/calc.asmx"; } If the Web service moves, youll have to modify the CS file and regenerate the proxy. To avoid having to update code when a Web services URL changes, you can use Wsdl.exes /appsettingurlkey (abbreviated /urlkey) switch. The command wsdl /urlkey:CalcUrl http://www.wintellect.com/calc.asmx produces the following class constructor: publicCalculatorWebService() { stringurlSetting = System.Configuration.ConfigurationSettings.AppSettings["CalcUrl"]; if ((urlSetting != null)) { this.Url = urlSetting; } else { this.Url = "http://www.wintellect.com/calc.asmx"; } } Now you can assign a value to CalcUrl in the appSettings section of a local Web.config file, like so: <configuration> <appSettings> <add key="CalcUrl" value="http://www.wintellect.com/calc.asmx" /> </appSettings> </configuration>

If the URL changes, you can update the proxy simply by editing Web.config. No code changes are required 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 a) CREATING APPLICATION POOLS(IIS 6.0)When we 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, we can assign specific configuration settings to a worker process (or, in the case of a Web garden, to a set of worker processes) that service a group of applications.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. Configuring Application Pools in IIS 6.0 (IIS 6.0): This feature of IIS 6.0 is available only when running in worker process isolation mode. An application pool is a configuration that links one or more applications to a set of one or more worker processes. Because applications in an application pool are separated from other applications by worker process boundaries, an application in one application pool is not affected by problems caused by applications in other application pools. By creating new application pools and assigning Web sites and applications to them, you can make your server more efficient and reliable, as well as making your other applications always available, even when the worker process serving the new application pool has problems. 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 applicationDEPLOYING ASP.NET APPLICATIONS

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. 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 sessionstate 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. 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. a) BASIC ARITHMETIC OPERATION: using System; class MainClass { static void Main(string[] args) { int a,b,c,d,e,f;

a = 1; b = a + 6; Console.WriteLine(b); c = b - 3; Console.WriteLine(c); d = c * 2; Console.WriteLine(d); e = d / 2; Console.WriteLine(e); f = e % 2; Console.WriteLine(f); } }

b) FINDING GREATER OF N NUMBERS public static void FindLargestAndSmallest() {

int arraySize; bool isNum; int largestNum; int[] numArray = new int[50] //ask the user for the size of their array Console.WriteLine("Enter the size of Array"); //read in the value string sizeString = Console.ReadLine(); //we will now use TryParse to get the numeric value entered isNum = Int32.TryParse(sizeString, out arraySize); //now we will determine if the value is numeric if (isNum) 6. Describe the steps involved in creating classes and objects with the help of a program in C#. A class is a construct that enables you to create your own custom types by grouping together variables of othertypes, methods and events. A class is like a blueprint. It defines the data and behavior of a type. If the class is notdeclared as static, client code can use it by creating objects or instances which are assigned to a variable. Thevariable remains in memory until all references to it go out of scope. At that time, the CLR marks it as eligible forgarbage collection. If the class is declared as static, then only one copy exists in memory and client code can onlyaccess it through the class itself, not an instance variable. For more information, see Static Classes and Static ClassMembers (C# Programming Guide). Unlike structs, classes support inheritance, a fundamental characteristic of object-oriented programming. 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; } } classTestPerson{static void Main() { Person person = new Person(); Console.WriteLine(person.name); person.SetName("John Smith"); Console.WriteLine(person.name); // Keep the console window 3 Console.WriteLine("Press any key to exit."); Console.ReadKey(); } } /* Output:unknownJohn Smith*/

You might also like