Home Random Page


CATEGORIES:

BiologyChemistryConstructionCultureEcologyEconomyElectronicsFinanceGeographyHistoryInformaticsLawMathematicsMechanicsMedicineOtherPedagogyPhilosophyPhysicsPolicyPsychologySociologySportTourism






Task 2 – Creating a new class utilizing Automatically Implemented Properties

In the following example, the Point class contains two properties:

public class Point

{

private int x;

private int y;

 

public int X { get { return x; } set { x = value; } }

public int Y { get { return y; } set { y = value; } }

}

 

To simplify this let the compiler generate the field and we can simply specify the property name as shown below:

 

public class Point

{

public int X { get; set; }

public int Y { get; set; }

}

 

1. In the Solution Explorer, double-click Program.cs to open the source code in the Visual C# code editor.

2. Add a Customer class to the NewLanguageFeatures namespace:

 

namespace NewLanguageFeatures

{

public class Customer

{

}

 

class Program

{

static void Main(string[] args)

{

}

}

}

 

3. In the Customer class, add two properties (Name and City) and override the ToString method to easily view the object.

 

public class Customer

{

public string Name { get; set; }

public string City { get; set; }

 

public override string ToString()

{

return Name + "\t" + City;

}

}

 

4. In the Main method, create a new instance of the Customer class.

 

static void Main(string[] args)

{

Customer c = new Customer();

c.Name = "Maria Anders";

c.City = "Berlin";

 

Console.WriteLine(c);

}

5. Press Ctrl+F5 to build and run the application, displaying the output in a console window:

6. Press any key to close the console window and terminate the program.

Creation of properties by this method require the properties to have both get and set accessors. However, accessors can still have modifiers applied to them as shown in the next Task.


Date: 2015-02-03; view: 673


<== previous page | next page ==>
Lab 1: C# 3.0 Language Enhancements | Task 3 – Use of Accessibility Modifiers with Properties
doclecture.net - lectures - 2014-2024 year. Copyright infringement or personal data (0.007 sec.)