Workshop
Quiz
-
What are the five access modifiers available in C#?
-
What is the default accessibility for a class?
-
What is a constructor?
-
Can the default constructor of a class have parameters?
-
Using the code shown in Listing 3.13, what is the output of the following statement?
C c = new C(3, "C2");
-
When can a read-only field be assigned?
-
What is method overloading?
-
Are there limitations when using automatic properties?
-
What is a nested class?
-
Can extension methods access private members of the type being extended?
-
What happens when the new operator is executed?
Answers
- The five access modifiers available in C# are public, protected, internal, protected internal, and private.
- Classes default to internal accessibility but are allowed to have either public or internal declared accessibility. Nested classes default to private accessibility but are allowed to have any accessibility.
- A constructor is a special method that is executed automatically when you create an object to provide additional initialization actions.
- No, the default constructor of a class must always have no parameters.
The output of the statement is
Default Constructor C2 3
- A read-only field can be initialized only as part of its declaration or in a constructor.
- Method overloading is creating more than one method of the same name that differs only by the number and type of parameters.
- Automatic properties do not provide a way to access the implicit backing field, do not enable you to specify additional statements that execute as part of the get or set accessor, and do not enable a mixture of regular and automatic syntax.
- A nested class is one that is fully enclosed inside another class declaration.
- Because extension methods are simply static methods, they do not have any special access to the type they extend. However, an extension method defined in the same assembly as the type being extended also has access to internal members of that type.
- The two primary actions that occur when the new operator is executed are 1) Memory is allocated from the heap and 2) the constructor for the class is executed to initialize the allocated memory.
Exercise
Add a class to the PhotoViewer project that represents a photo. This class should be named Photo and be in the PhotoViewer namespace. The class should have the following private fields and a read-only property to retrieve the value of those fields:
Data Type
Field Name
bool
Exists
BitmapFrame
image
Uri
source
Add the following constructor:
public Photo(Uri path) { if (path.IsFile) { this.source = path; } }