Questions
-
What is the right syntax for an automatic property? Select all that apply.
-
public int Width { get; set; } -
public int Width { set; get; } -
public int Width { Set; Get; } -
public int Width { Get; Set; } -
public int Width { set(); get();} -
public int Width { get(); set();}
-
-
Which of the following statements is false?
- Properties can be static.
-
getandsetaccessors must always have bodies. - Properties have headers.
-
getandsetaccessors correspond to “getter” and “setter” methods for attributes.
-
Consider the following implementation of a class called
Pet:class Pet{ private string name; public string Name{ get; set { name = value; } } }This code will give a compilation error. Why?
- The
setaccessor has a body, but thegetaccessor does not. - The instance variable for
nameis declared, but no value is assigned. -
valueis not a keyword and hasn’t been declared, so it is meaningless here. - The access modifier for
nameisprivate, but it should bepublic.
- The
Circle Example
For the following questions, imagine you’ve implemented a Circle
class, with the attribute private decimal diameter; and a “getter” and
“setter” method for that attribute. You’ve created an object in this
Circle class called myCircle. If you were to implement the class
with properties instead:
-
What would calling the
getaccessor do?- Return the value of
diameter - Assign a value to
diameter
- Return the value of
-
What would calling the
setaccessor do?- Return the value of
diameter - Assign a value to
diameter
- Return the value of
-
The statement
myCircle.GetDiameter();would have to be rewritten. How would you rewrite it?-
myCircle.Diameter; -
myCircle.diameter; -
Diameter.myCircle; -
myCircle = Diameter;
-
-
The statement
myCircle.SetDiameter(5.0m);would also need to be rewritten. How would you rewrite it?-
myCircle.diameter = 5.0m; -
Diameter.myCircle(5.0m); -
myCircle.Diameter = 5.0m; -
myCircle.diameter(5.0m);
-
You would now like to add a Color property of type string to your
Circle class.
-
How would you declare the instance variable?
-
public color string; -
public string Color; -
private string Color; -
private string color;
-
-
How would you format the property header?
-
public string color; -
public string Color; -
private Color string; -
private string color;
-
-
What would the
getaccessor’s body look like, in its most basic possible form?-
color; -
color = value; -
return color; -
string color;
-
-
What would the
setaccessor’s body look like, in its most basic possible form?-
color; -
color = value; -
return color; -
string color;
-
-
In the
Mainmethod, you would like to assign the value"yellow"tocolor. Which statement would do that?-
yellow.myCircle; -
myCircle.Color = "yellow"; -
myCircle.yellow = Color; -
myCircle = "yellow";
-
Plant Example
For the next questions, consider the following implementation of a class
called Plant:
class Plant{
private string species;
public string Species
{get;} = "Helianthus annus";
private static bool hasChloroplasts;
public static bool HasChloroplasts
{get;} = true;
}-
Will this code compile? Why or why not?
- No, because there are no
setaccessors, and properties must have one. - No, because a property cannot be assigned a default value.
- No, because a
getaccessor must always have a body. - Yes, because properties are not required to have
setaccessors. - Yes, because a default value must be assigned for each property.
- No, because there are no
Suppose you’ve created an object in the Plant class called myPlant.
-
In the Main method, what would the statement
Console.Write(myPlant.Species);do?
- Display the current value of
species,"Helianthus annus". - Rename the
myPlantobject toSpecies. - It won’t do anything—the code for the class doesn’t compile.
- It won’t do anything—the property is write-only.
- Display the current value of
-
The
HasChloroplastsproperty isstatic. What does this mean? Select all that apply.- Every object in the
Plantclass has its ownHasChloroplastsproperty. - The property is shared across the class and all of its instances.
- The property can be accessed without creating a
Plantobject. - The property’s value cannot be changed from the default.
- Every object in the
-
The statement
myPlant.Species = "Coffea arabica";would not compile. Why not?- The syntax is wrong.
- Only a
staticproperty’s default value can be changed. - The code for the class doesn’t compile.
- The property only has a
getaccessor, so it is read-only.
-
What modification to the
Plantclass would allow the statementmyPlant.Species = "Coffea arabica";to compile?- Remove the default value,
"Helianthus annus". - Add
set;to theSpeciesproperty. - Add
set;to theHasChloroplastsproperty. - Make the entire class
static. - Change the access modifier for
speciesfromprivatetopublic
- Remove the default value,
Problems
-
Consider the following implementation of a
Rectangleclass:class Rectangle { private int length; private int width; public void SetLength(int lengthParameter) { length = lengthParameter; } public int GetLength() { return length; } public void SetWidth(int widthParameter) { width = widthParameter; } public int GetWidth() { return width; } public int ComputeArea() { return length * width; } }-
Write a
Mainmethod that-
Creates a
Rectangleobject, -
Sets its width to 5,
-
Sets its length to 10,
-
Displays its area.
Solution
using System; class Program { public static void Main() { Rectangle test = new Rectangle(); // 1 test.SetWidth(5); // 2 test.SetLength(10); // 3 Console.WriteLine(test.ComputeArea()); // 4 } }
-
-
Write an implementation of the
Rectangleclass using only properties (included for theComputeArea()).Solution
class Rectangle{ public int Length{get; set;} public int Width{get; set;} public int Area{get{return Length * Width;}} } -
Write a
Mainmethod that performs the same tasks as above, but using the properties you just defined.Solution
using System; class Program { public static void Main() { Rectangle test = new Rectangle(); // 1 test.Width = 5; // 2 test.Length = 10; // 3 Console.WriteLine(test.Area); // 4 } }
-
-
Implement a
SDCardclass to represent SD cards. Add attributes to your answer if needed.-
Implement a
Nicknamestringproperty using automatic properties.Solution
public string Nickname {get; set;} -
Implement a
Capacityintproperty whose setter raises anArgumentExceptionexception if the value passed as argument is not 8, 16, 32, 64 or 128. The getter should simply return the value stored.Solution
private int capacity; public int Capacity { set { if (value == 8 || value == 16 || value == 32 || value == 64 || value == 128) capacity = value; else throw new ArgumentException(); } get { return capacity; } } -
Implement a
CapacityInGbintproperty with only a getter, that returns theCapacitytimes 8.Solution
public int CapacityInGb { get {return capacity * 8;} } -
Implement a
ToStringmethod that returns astringcontaining the nickname of the SD card, its capacity in gigabytes (GB, from question 2.), and its capacity in gigabits (Gb, from question 3.).Solution
public override string ToString(){ return "Name: " + Nickname + "\nCapacity: " + Capacity + "GB" + "\nCapacity in Gb: " + CapacityInGb + "Gb"; }
Solution
A complete solution gives:
using System; class SDCard { public string Nickname { get; set; } private int capacity; public int Capacity { set { if ( value == 8 || value == 16 || value == 32 || value == 64 || value == 128 ) capacity = value; else throw new ArgumentException(); } get { return capacity; } } public int CapacityInGb { get { return capacity * 8; } } public override string ToString() { return "Name: " + Nickname + "\nCapacity: " + Capacity + "GB" + "\nCapacity in Gb: " + CapacityInGb + "Gb"; } }(Download this code) And a possible test program is:
using System; class Program { static void Main() { SDCard test = new SDCard(); test.Nickname = "Blue"; test.Capacity = 8; Console.WriteLine(test); try { test.Capacity = 7; } catch (Exception e) { Console.WriteLine(e.Message); } } } -
-
In this problem, we will implement a
Weatherclass recording a location and a temperature (in Fahrenheit). Add attributes to your answers if needed.-
Implement a
Locationstringproperty using automatic properties. Its default value should be “Unknown”.Solution
public string Location { get; set; } = "Unknown"; -
Implement a
Temperaturedoubleproperty. If the value passed as an argument to the setter is less than -128.6 or greater than 134.1, then the setter should raise anArgumentOutOfRangeExceptionexception. The getter simply returns the value stored.Solution
public double Temp { set { if (value < -128.6 || value > 134.1) throw new ArgumentOutOfRangeException(); else { temp = value; } } get { return temp; } } -
Implement a
TempInCdoubleproperty with only a getter that returns the temperature in Celsius, using the following formula: .Solution
public double TempInC { get { return (Temp - 32) / (9 / 5); } } -
Implement a
ToStringmethod that returns astringcontaining the location and the temperature both in Celsius and Fahrenheit.Solution
public override string ToString() { return Location + ": " + Temp + "°F (" + TempInC + "°C)"; }
-