Chapter 5: Building Your Own Types with Object-Oriented Programming [Flashcarder]

1
Q

What are the primary types of members that an object-oriented type in C# can have?

A

Fields to store data and methods to perform actions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Which OOP concepts are used to combine related data and actions in a type?

A

Encapsulation

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is aggregation in object-oriented programming?

A

Aggregation refers to combining objects to form a new component. For example, a Person and a Car object can be aggregated when the Person becomes the Driver.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the difference between composition and aggregation in OOP?

A

Composition defines what an object is made of (e.g., a Car is composed of Wheels and an Engine), while aggregation refers to objects that can work together (e.g., a Person can drive a Car, but they are separate entities).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How is inheritance used in C#?

A

Inheritance allows a subclass to derive from a base class, inheriting all its functionality. The derived class can also extend or override certain functionality.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is abstraction in OOP, and how is it implemented in C#?

A

Abstraction captures the core idea of an object and hides the details. It is implemented using abstract classes and interfaces.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What keyword is used to define an abstract class in C#?

A

The abstract keyword.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is polymorphism in OOP?

A

Polymorphism allows a derived class to override an inherited method to provide custom behavior.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What are the keywords used in C# to define an object type?

A

class, record, and struct.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What C# keyword is used to restrict access to a class’s internal data?

A

private

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the purpose of class library assemblies in .NET?

A

Class library assemblies group types together into easily deployable units, such as DLL files, to make code reusable across multiple projects.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How do you create a new class library in .NET using Visual Studio?

A

Select “Class Library” as the project template, name the project (e.g., PacktLibraryNetStandard2), and specify the solution folder (e.g., Chapter05).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is the default target framework for class libraries created with the .NET 8 SDK?

A

The default target framework is .NET 8.0.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How can you modify a class library project to target .NET Standard 2.0 and use the C# 12 compiler?

A

Modify the <TargetFramework> to netstandard2.0, add <LangVersion>12</LangVersion>, and import the System.Console class statically for all C# files.</TargetFramework>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Why can’t all modern C# features be used in a .NET Standard 2.0 class library?

A

Some modern C# features, like default implementations in interfaces (C# 8) or the required keyword (C# 11), require newer .NET runtimes, such as .NET Standard 2.1 or .NET 7.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is the recommended practice for supporting both modern and legacy .NET platforms in class libraries?

A

For modern features, use a .NET 8 class library. To support legacy platforms like .NET Framework and Xamarin, create a .NET Standard 2.0 class library and override the default C# 7 compiler to a newer version.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

How do you compile a .NET class library in Visual Studio 2022?

A

Navigate to Build | Build <ProjectName> (e.g., Build PacktLibraryNetStandard2).</ProjectName>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

How do you traditionally define a type such as a class in a namespace in C#?

A

Types are defined within curly braces inside a namespace block. For example:
~~~
namespace Packt.Shared
{
public class Person
{
}
}
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is a file-scoped namespace in C# and how is it different from traditional namespaces?

A

A file-scoped namespace simplifies code by ending the namespace declaration with a semicolon and removing the curly braces, allowing all types in the file to be part of the namespace without indentation. Example:
~~~
namespace Packt.Shared;
public class Person
{
}
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Why is it considered good practice to put each type in its own code file or group types in the same namespace in a file?

A

It allows for the use of file-scoped namespaces, simplifying the structure and making the code easier to manage.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Why should classes be placed in a logically named namespace?

A

Logical namespaces, such as domain-specific ones (e.g., System.Numerics), help clarify the purpose of the types. For generic types without a domain, a more general namespace like Packt.Shared can be used.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What is the default access modifier for a class in C# if none is specified?

A

The default access modifier for a class is internal, meaning it is accessible only within its own assembly.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What does the public access modifier do when applied to a class in C#?

A

It allows the class to be accessible from other assemblies, making it available for use outside its own assembly.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What is the use of the file access modifier introduced in .NET 7?

A

The file access modifier restricts the visibility of a type to only the code file in which it is defined. This is rarely used but can be helpful in scenarios like source generators.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

What is the recommended practice for using access modifiers on class members?

A

Always explicitly specify access modifiers, with public and internal being the most common. For clarity, avoid relying on default modifiers.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

What are fields in C#?

A

Fields are used to store data and can be thought of as variables that belong to a type.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

What are the three specialized categories of fields in C#?

A

The three specialized categories of fields are:
1. Constant: Data that never changes.
2. Read-only: Data that cannot change after the class is instantiated.
3. Event: Data that references methods to execute when an event occurs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

What is an example of a constant field in C#?

A

An example is byte.MaxValue, which is always 255.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

What is a read-only field, and how is it different from a constant field?

A

A read-only field cannot change after instantiation but can be calculated or loaded at runtime, such as DateTime.UnixEpoch, which represents January 1, 1970.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

What are methods in C# used for?

A

Methods are used to execute statements in a program.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

What are the four specialized categories of methods in C#?

A

The four specialized categories are:
1. Constructor
2. Property
3. Indexer
4. Operator

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

What is the purpose of a constructor method in C#?

A

A constructor executes when the new keyword is used to instantiate a class, such as new DateTime(2023, 12, 25) to instantiate Christmas Day 2023.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

What is the difference between a property and a field in C#?

A

A property is a specialized method that executes when data is accessed or modified, commonly used to encapsulate fields and control access to the data.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

What is an indexer in C#?

A

An indexer allows data to be accessed using array-like syntax, such as name[0] to get the first character of the string name.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

What is the role of an operator method in C#?

A

Operator methods define the behavior when applying operators like + or / to operands of a custom type.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

How do you import a namespace to use a type in another project in C#?

A

You can import a namespace by adding a reference to the assembly containing the type and using the using statement to include the namespace at the top of the file.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

How do you instantiate a class in C# using modern syntax?

A

You can instantiate a class using the new keyword. For example, Person bob = new(); uses C# 9 syntax to instantiate the Person class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

Why does the Person class in C# have a ToString method, even when the class is empty?

A

All C# classes inherit from System.Object, which provides the ToString method. The default implementation returns the full namespace and type name of the object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

What is the significance of inheriting from System.Object in C#?

A

All types in C# inherit from System.Object either directly or indirectly. It provides fundamental methods like ToString, Equals, and GetHashCode to all objects.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

What is the purpose of explicitly inheriting from System.Object in C#?

A

Although not required, you can explicitly inherit from System.Object for clarity. For example, public class Person : object makes the inheritance explicit.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

How can you avoid namespace conflicts when two namespaces contain types with the same name?

A

Use an alias for one of the namespaces to resolve conflicts. For example, using Tx = Texas; allows you to use Tx.Paris to differentiate between Texas.Paris and France.Paris.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

How do you rename a type using an alias in C#?

A

You can rename a type using an alias with the using statement. For example, using Env = System.Environment; allows you to refer to System.Environment as Env throughout your code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

What are fields in C# and what are they used for?

A

Fields are used to store data in a class. They can be thought of as variables that belong to a type.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

How would you define two public fields in a Person class to store a person’s name and birth date?

A
public class Person {
    public string? Name; // Can be null
    public DateTimeOffset Born; // Stores date, time, and UTC offset
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

What is the difference between DateOnly, DateTime, and DateTimeOffset for storing date-related information?

A
  • DateOnly: Stores only the date without time.
  • DateTime: Stores both date and time, but it varies between local and UTC time.
  • DateTimeOffset: Stores date, time, and UTC offset, accounting for time zones.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

Since C# 8, how does the compiler handle reference types like string that can be null?

A

The compiler warns if a reference type could be null and potentially throw a NullReferenceException. You can use a ? to indicate a nullable type, removing the warning.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

What are the six possible combinations of member access modifiers in C#?

A
  1. private: Accessible inside the type only (default).
  2. internal: Accessible inside the type and any type in the same assembly.
  3. protected: Accessible inside the type and any type that inherits from the type.
  4. public: Accessible everywhere.
  5. internal protected: Accessible inside the type, any type in the same assembly, and any type that inherits from the type.
  6. private protected: Accessible inside the type and any type that inherits from the type and is in the same assembly (C# 7.2 or later).
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q

What is a good practice when applying access modifiers to fields in a class?

A

Always explicitly apply an access modifier, even when using the implicit private modifier. Fields should usually be private or protected, with public properties created to control access.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q

How do you set a person’s name and birth date using field values in C#?

A

You can set the values as follows:
~~~
bob.Name = “Bob Smith”;
bob.Born = new DateTimeOffset(1965, 12, 22, 16, 28, 0, TimeSpan.FromHours(-5));
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
50
Q

How can you format a date in C# to display a long date format?

A

You can use the format specifier D for a long date format, e.g., WriteLine(“{0} was born on {1:D}.”, bob.Name, bob.Born);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
51
Q

What is object initializer syntax and how would you use it to instantiate a person named Alice in C#?

A

Object initializer syntax allows you to initialize an object in a concise way using curly braces. Example:
~~~
Person alice = new() {
Name = “Alice Jones”,
Born = new DateTimeOffset(1998, 3, 7, 16, 28, 0, TimeSpan.Zero)
};
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
52
Q

What is a good practice when passing multiple arguments, particularly for complex types like DateTimeOffset?

A

Use named parameters to pass arguments, which makes the purpose of each argument clearer.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
53
Q

What is an enum type in C# and when would you use it?

A

An enum type is used to store a value that is one of a limited set of options, such as the ancient wonders of the world. For example:
~~~
public enum WondersOfTheAncientWorld {
GreatPyramidOfGiza,
HangingGardensOfBabylon,
StatueOfZeusAtOlympia,
// others
}
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
54
Q

How do you set and output an enum value in C#?

A

You can set an enum field like this:
~~~
bob.FavoriteAncientWonder = WondersOfTheAncientWorld.StatueOfZeusAtOlympia;
WriteLine(“{0}’s favorite wonder is {1}.”, bob.Name, bob.FavoriteAncientWonder);
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
55
Q

How are enum values stored internally in C#?

A

Enum values are stored as integers, with the values automatically starting at 0 unless specified otherwise. For example, the StatueOfZeusAtOlympia might be stored as 2.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
56
Q

How do you store multiple enum values in a single field in C#?

A

You can use the [Flags] attribute on the enum and combine values using the bitwise OR (|) operator. For example:
~~~
[Flags]
public enum WondersOfTheAncientWorld : byte {
GreatPyramidOfGiza = 1,
HangingGardensOfBabylon = 2,
MausoleumAtHalicarnassus = 16
}

bob.BucketList = WondersOfTheAncientWorld.HangingGardensOfBabylon
| WondersOfTheAncientWorld.MausoleumAtHalicarnassus;
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
57
Q

Why is it useful to use the [Flags] attribute on an enum?

A

The [Flags] attribute allows an enum to represent a combination of values, storing multiple options in a single variable and displaying them as a comma-separated string instead of an integer.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
58
Q

How are enum values stored in memory when using the [Flags] attribute?

A

Each enum value is stored as a bit in memory. The values are designed to not overlap, using bitwise flags to combine them. For example:
* HangingGardensOfBabylon = 0b_0000_0010 (2)
* MausoleumAtHalicarnassus = 0b_0001_0000 (16) Combining these results in a value of 18.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
59
Q

What is a good practice when using enum types to store combinations of values?

A

Use an enum derived from byte if there are up to eight options, from ushort for up to 16 options, from uint for up to 32 options, and from ulong for up to 64 options.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
60
Q

How would you output a person’s bucket list of wonders using the [Flags] attribute?

A

After setting the bucket list values, you can output the combined enum values:
WriteLine($"{bob.Name}'s bucket list is {bob.BucketList}.");

Example output:
“Bob Smith’s bucket list is HangingGardensOfBabylon, MausoleumAtHalicarnassus.”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
61
Q

What is an example of aggregation in C# using a collection?

A

Aggregation in C# can be represented by storing related instances of a class in a collection. For example, a Person class can store multiple Person instances representing children in a List<Person>, where the children are related but not part of the Person itself.</Person>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
62
Q

How do you define a field in C# to store multiple instances of a class?

A

Use a generic collection type like List<T> to store multiple instances of a class. Example:
`public List<Person> Children = new();`</Person></T>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
63
Q

What is the significance of initializing a List<T> in C# before adding items to it?</T>

A

Initializing a List<T> ensures the field is not null. If not initialized, attempting to use members like Add will result in a runtime exception.</T>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
64
Q

What are generics in C# and why are they used with collections?

A

Generics allow collections to be strongly typed, improving performance and correctness by enabling the compiler to know the exact type of objects stored in the collection. This prevents runtime errors and enhances type safety.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
65
Q

How do you add items to a generic List<T> in C#?</T>

A

You can add items to a List<T> using the Add method. For example:
`bob.Children.Add(new Person { Name = "Bella" });`</T>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
66
Q

What are the different versions of C# that allow adding children to a List<Person> in different ways?</Person>

A
  • C# 1 or later: Person alfred = new Person();
  • C# 3 or later: bob.Children.Add(new Person { Name = “Bella” });
  • C# 9 or later: bob.Children.Add(new() { Name = “Zoe” });
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
67
Q

What keyword is used in C# to create a constant field, and what is the restriction of such a field?

A

The const keyword is used to create a constant field in C#. The restriction is that the value of a constant field must be known at compile time and cannot be changed afterwards.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
68
Q

How is a constant field accessed in C#?

A

A constant field is accessed using the class name rather than the instance of the class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
69
Q

Why might read-only fields be preferred over constant fields?

A

Read-only fields are preferred when the value can only be set at runtime and can be calculated or loaded from an external source. Unlike constants, they are not replaced by literal values at compile time and can reflect changes in future versions without recompiling.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
70
Q

What is the difference between a const field and a readonly field in C#?

A

A const field must be set at compile time and cannot change, whereas a readonly field can be set at runtime, typically in the constructor, and it cannot change after being initialized.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
71
Q

What happens if you attempt to change a readonly field after it has been set in C#?

A

It will result in a compile-time error, as readonly fields can only be set during initialization or in a constructor and cannot be modified thereafter.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
72
Q

What is the significance of the required modifier introduced in C# 11?

A

The required modifier ensures that certain fields or properties must be assigned a value when an instance of the class is created. It is enforced by the compiler to prevent the omission of these fields during instantiation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
73
Q

What C# version and .NET target are required to use the required modifier?

A

The required modifier requires C# 11 and .NET 7 or later.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
74
Q

How would you instantiate a Book class with required fields in C# 11?

A

You can instantiate a Book class by specifying the required fields either through object initializer syntax or by using a constructor that takes the required parameters. For example:
Book book = new() { Isbn = "978-1803237800", Title = "C# 12 and .NET 8 - Modern Cross-Platform Development Fundamentals" };

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
75
Q

What is the purpose of a constructor in C#?

A

A constructor is a special method used to initialize fields of a class when an instance of that class is created using the new keyword.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
76
Q

How are read-only fields initialized in a constructor?

A

Read-only fields can be initialized within a constructor, allowing them to be set at runtime but preventing them from being modified later.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
77
Q

What does the following C# code do?
public Person() { Name = "Unknown"; Instantiated = DateTime.Now; }

A

This constructor initializes the Name field to “Unknown” and the Instantiated field to the current date and time when a Person object is instantiated.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
78
Q

What happens if a class has multiple constructors?

A

Multiple constructors allow a class to be instantiated with different sets of initial values for its fields, providing flexibility for object creation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
79
Q

How do you define a constructor that accepts parameters for initializing fields?

A

You define a constructor with parameters like this:
public Person(string initialName, string homePlanet) { Name = initialName; HomePlanet = homePlanet; Instantiated = DateTime.Now; }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
80
Q

How would you instantiate a Person object using a constructor with parameters in C#?

A

You can instantiate it as follows:
Person gunny = new(initialName: "Gunny", homePlanet: "Mars");

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
81
Q

What is the output of the following C# code?
Person blankPerson = new(); WriteLine($"{blankPerson.Name} of {blankPerson.HomePlanet} was created at {blankPerson.Instantiated:hh:mm:ss} on a {blankPerson.Instantiated:dddd}.");

A

The output will be:
Unknown of Earth was created at [current time] on a [current day of the week].

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
82
Q

Why is it beneficial to have multiple constructors in a class?

A

Multiple constructors provide the flexibility to initialize an object with different sets of initial values, encouraging developers to provide meaningful data when creating instances.

83
Q

What is the purpose of the const keyword in C#?

A

The const keyword is used to declare a field whose value is set at compile time and cannot be changed. If an attempt is made to change the value, a compile-time error will occur.

84
Q

How do you access a const field in C#?

A

To access a const field, you use the class name, not the instance. For example, Person.Species accesses the const field Species in the Person class.

85
Q

To access a const field, you use the class name, not the instance. For example, Person.Species accesses the const field Species in the Person class.

A

const fields are set at compile time and cannot change, while readonly fields are set at runtime, either at the time of declaration or in the constructor, and cannot be modified after initialization.

86
Q

readonly fields can be set at runtime, allowing values to be calculated or loaded dynamically.

A

The value of readonly fields is not replaced with a literal at compile time, so changes are reflected immediately without recompiling.

87
Q

How can you ensure a field in a class must be initialized when the object is created?

A

You can use the required modifier introduced in C# 11, which ensures that the field or property must be set when the object is instantiated.

88
Q

What is the use of the [SetsRequiredMembers] attribute in C#?

A

The [SetsRequiredMembers] attribute tells the compiler that a constructor sets all the required fields and properties, allowing the constructor to avoid compiler errors related to required members.

89
Q

How do you use object initializer syntax to instantiate a class and set its properties?

A

You can use curly braces after instantiating a class to set its properties, like this:
Book book = new() { Isbn = "978-1803237800", Title = "C# 12 and .NET 8" };

90
Q

What is a method in C#?

A

A method in C# is a member of a type that executes a block of statements. It can either return a value or perform an action without returning any value (indicated by void).

91
Q

How do you define a method in C# that does not return any value?

A

A method that does not return any value is defined with the void keyword before the method name.

92
Q

How do you define a method in C# that returns a value?

A

A method that returns a value is defined with the return type before the method name. For example, public string GetOrigin() returns a string value.

93
Q

What does the WriteToConsole method do in the Person class?

A

The WriteToConsole method writes the person’s name and day of birth to the console in the format: “{Name} was born on a {Born:dddd}.”.

94
Q

What does the GetOrigin method return in the Person class?

A

The GetOrigin method returns a string stating the person’s name and home planet in the format: “{Name} was born on {HomePlanet}.”.

95
Q

How are parameters defined in methods in C#?

A

Parameters in methods are defined inside the parentheses of the method declaration, similar to variable declarations.

96
Q

What does the method SayHello() do in the Person class?

A

The SayHello() method returns a string saying the person’s name followed by ‘says Hello!’, for example: “{Name} says ‘Hello!’”.

97
Q

What is method overloading in C#?

A

Method overloading is when multiple methods share the same name but have different parameter types or numbers of parameters, allowing the same method name to be used for different scenarios.

98
Q

What is the signature of a method in C#?

A

The signature of a method is the list of parameter types that can be passed when calling the method. Overloaded methods must differ in their signature.

99
Q

What happens if two overloaded methods have the same parameter list but different return types?

A

Two overloaded methods cannot have the same parameter list and differ only by their return types. This will cause a compile-time error.

100
Q

What is an optional parameter in C#?

A

An optional parameter in C# is a parameter that has a default value assigned in the method parameter list, and it must come last in the list of parameters. This allows the method to be called without explicitly passing a value for that parameter.

101
Q

How do you make a parameter optional in a method?

A

You make a parameter optional by assigning a default value inside the method parameter list. Optional parameters must always come last in the list of parameters.

102
Q

What is the output of the following code in C#?
WriteLine(bob.OptionalParameters());

A

The output is: command is Run!, number is 0, active is True.

103
Q

How can you pass parameters using named arguments in C#?

A

You can pass parameters by explicitly naming them, allowing you to pass values in a different order than how they are declared. For example:
WriteLine(bob.OptionalParameters(number: 52.7, command: "Hide!"));

104
Q

What happens when you mix positional and named parameters in C#?

A

In C#, you can mix positional and named parameters, but named parameters must follow the positional ones. For example:
WriteLine(bob.OptionalParameters("Poke!", active: false));

This will output: command is Poke!, number is 0, active is False.

105
Q

Why should optional parameters be placed after all required parameters?

A

Optional parameters must come after all required parameters because the compiler requires a clear distinction between required values that must always be passed and optional ones that can be skipped.

106
Q

How do you add a required parameter to a method that has optional parameters?

A

You must place the required parameter before the optional parameters. For example:
public string OptionalParameters(int count, string command = "Run!", double number = 0.0, bool active = true)

107
Q

What is the advantage of using named arguments when calling methods with optional parameters?

A

Named arguments provide clarity and flexibility, allowing the caller to skip certain optional parameters or pass values out of order, which can make the method calls easier to read and understand.

108
Q

What are the different ways a parameter can be passed into a method in C#?

A

Parameters can be passed in the following ways:
1. By value (default): Affects only the parameter in the method, not the original variable.
1. As an out parameter: Must be initialized inside the method and passed out.
1. By reference (ref parameter): Allows the value to be passed in and modified.
1. As an in parameter: Passed by reference but read-only.

109
Q

What is an out parameter, and how is it used in a method?

A

An out parameter is used to pass a value out of a method. It must be initialized inside the method, and the method caller receives the modified value after the method executes. For example:
~~~
public void ExampleMethod(out int result) {
result = 10; // Must be initialized inside the method
}
~~~

110
Q

What is a ref parameter, and how is it different from an out parameter?

A

A ref parameter allows both the value to be passed into the method and modified inside it. Unlike out parameters, ref parameters must be initialized before being passed to the method. For example:
~~~
public void ModifyValue(ref int number) {
number++; // Modifies the original variable
}
~~~

111
Q

What does an in parameter do in C#?

A

An in parameter allows a reference to be passed to a method, but it is read-only inside the method. The method cannot modify the value. It is useful when you want to avoid copying large objects but still want them protected from modification.

112
Q

In what scenarios would you use the ref keyword in C#?

A

You use the ref keyword when you want a method to modify a value and have the changes reflect outside the method. It is especially useful when working with large objects to avoid copying and directly work with the memory reference.

113
Q

How does C# handle parameters passed by value (the default)?

A

When parameters are passed by value, the method gets a copy of the original value. Any changes to the parameter inside the method do not affect the original variable. This is the default behavior in C#.

114
Q

What happens if you try to modify an in parameter inside a method?

A

Attempting to modify an in parameter inside a method will result in a compiler error, as in parameters are read-only.

115
Q

What keyword can be used in C# 7 or later to return a reference to an internal variable from a method?

A

The ref keyword can be used in C# 7 or later to return a reference to an internal variable from a method.

116
Q

What are tuples in C#, and why are they used?

A

Tuples are an efficient way to combine two or more values into a single unit in C#. They are used to return multiple values from a method without creating a new class.

117
Q

What is the difference between the System.Tuple type and the System.ValueTuple type in C#?

A

System.Tuple was introduced in .NET 4, while System.ValueTuple was introduced with C# 7. The ValueTuple type is more efficient in common scenarios.

118
Q

How do you define a method that returns a tuple in C#?

A

A method that returns a tuple can be defined like this:
~~~
public (string, int) GetFruit()
{
return (“Apples”, 5);
}
~~~

119
Q

How are tuple fields named by default in C#?

A

By default, tuple fields are named Item1, Item2, and so on.

120
Q

How can you explicitly name the fields of a tuple in C#?

A

You can explicitly name the fields of a tuple by specifying names when returning it, such as:
~~~
public (string Name, int Number) GetNamedFruit()
{
return (Name: “Apples”, Number: 5);
}
~~~

121
Q

What is tuple name inference, and when was it introduced in C#?

A

Tuple name inference, introduced in C# 7.1, allows tuples to infer field names from the variables used to construct them.

122
Q

What C# version introduced the ability to alias tuples, and how is this done?

A

C# 12 introduced the ability to alias tuples. This can be done like this:
using Fruit = (string Name, int Number);

123
Q

How can tuples be deconstructed in C#?

A

Tuples can be deconstructed into separate variables using a deconstruction statement, such as:
(string fruitName, int fruitNumber) = bob.GetFruit();

124
Q

What are deconstructors in C#, and how do they work?

A

Deconstructors are special methods that break down an object into parts. They are implicitly called when an object is assigned to a tuple variable.

125
Q

What feature was introduced in C# 12 for tuples?

A

C# 12 introduced the ability to alias tuples, allowing you to name a tuple type and use it as the type name when declaring variables and parameters.

126
Q

How do you alias a tuple type in C# 12?

A

You can alias a tuple type in C# 12 using the using keyword. For example:
using Fruit = (string Name, int Number);

127
Q

What naming convention should be used when aliasing tuple parameters in C# 12?

A

When aliasing tuples in C# 12, you should use the title case naming convention for the parameters, for example, Name, Number, and BirthDate.

128
Q

How can you use an aliased tuple type in a method call in C# 12?

A

You can use an aliased tuple type in a method call like this:
Fruit fruitNamed = bob.GetNamedFruit();

129
Q

How do you deconstruct a tuple in C#?

A

To deconstruct a tuple, you can assign its components to separate variables using syntax like:
(string name, int number) = bob.GetNamedFruit();

130
Q

What is the result of deconstructing the tuple returned from the GetFruit method in C#?

A

The result of deconstructing the tuple returned from the GetFruit method might look like:
Deconstructed tuple: Apples, 5

131
Q

What types can have deconstruction methods in C#?

A

Any type can have deconstruction methods, not just tuples, as long as the type defines Deconstruct methods.

132
Q

How many Deconstruct methods can a type have?

A

A type can have as many Deconstruct methods as needed, as long as each method has a different signature.

133
Q

What does a Deconstruct method do in C#?

A

A Deconstruct method breaks down an object into parts, allowing it to be assigned to a tuple or separate variables.

134
Q

How do you deconstruct an object using a Deconstruct method?

A

Deconstruction is implicit when an object is assigned to a tuple, as in:
var (name, dob) = bob;

135
Q

What are the components of the following deconstruction method for a Person object in C#?
public void Deconstruct(out string? name, out DateTimeOffset dob)

A

This method deconstructs the Person object into two parts: name and dob, representing the name and date of birth.

136
Q

In the context of deconstruction, what does the following code do?
var (name, dob, fav) = bob;

A

This line deconstructs the bob object into three variables: name, dob (date of birth), and fav (favorite ancient wonder).

137
Q

Is the Deconstruct method explicitly called when deconstructing an object in C#?

A

No, the Deconstruct method is called implicitly when assigning an object to a tuple variable.

138
Q

What is a local function in C#?

A

A local function is a method defined within another method, accessible only from within the containing method.

139
Q

When were local functions introduced in C#?

A

Local functions were introduced in C# 7.

140
Q

How can you use a local function to calculate a factorial in C#?

A

You can use a local function like this:
~~~
public static int Factorial(int number) {
if (number < 0) throw new ArgumentException();
return localFactorial(number);

int localFactorial(int localNumber) {
if (localNumber == 0) return 1;
return localNumber * localFactorial(localNumber - 1);
}
}
~~~

141
Q

Can local functions throw exceptions?

A

Yes, local functions can throw exceptions just like other methods. For example, if the input is invalid, a local function can throw an ArgumentException.

142
Q

What is the purpose of the partial keyword in C#?

A

The partial keyword allows the definition of a class or method to be split across multiple files.

143
Q

How do you declare a partial class in C#?

A

You declare a partial class using the partial keyword, for example:
public partial class Person { }

144
Q

What happens if one part of a partial class is missing the partial keyword?

A

If one part of a partial class is missing the partial keyword, you will get a compilation error (CS0260).

145
Q

What is a typical use case for using partial classes in large projects?

A

Partial classes are useful in large projects where different parts of a class are auto-generated, such as when using an ORM to map database schemas.

146
Q

What is a property in C#?

A

A property in C# is a method (or pair of methods) that acts and looks like a field but provides additional functionality like validation when getting or setting values.

147
Q

How does a property differ from a field in C#?

A

A field provides a memory address to data, while a property does not. Properties provide more control by executing statements when data is accessed or modified.

148
Q

What is a read-only property in C#?

A

A read-only property in C# only has a get implementation, meaning it can only return values but cannot be set from outside the class.

149
Q

How is a read-only property defined using C# 1-5 syntax?

A

A read-only property is defined with only a get method, like this:
~~~
public string Origin
{
get { return string.Format(“{0} was born on {1}.”, Name, HomePlanet); }
}
~~~

150
Q

How can a property be defined using C# 6 and later syntax?

A

Using lambda expression body syntax, a read-only property can be written as:
public string Greeting => $"{Name} says 'Hello!'";

151
Q

How can you calculate a person’s age using a read-only property in C#?

A

The Age property can be calculated using:
public int Age => DateTime.Today.Year - Born.Year;

152
Q

How do you access properties in a C# class?

A

Properties can be accessed just like fields, for example:
~~~
WriteLine(sam.Origin);
WriteLine(sam.Greeting);
WriteLine(sam.Age);
~~~

153
Q

How do you create a settable property in C# using older syntax?

A

You must provide both a get and set method using the following syntax:
public string? FavoriteIceCream { get; set; }

154
Q

What is automatically created by the compiler when you define a property using C# auto-syntax?

A

A backing field is automatically created by the compiler to store the value of the property.

155
Q

Why would you manually create a private field for a property?

A

You need more control over what happens when a property is set, such as adding validation logic.

156
Q

How do you manually define a private backing field for a property in C#?

A

You can define a private backing field as follows:
private string? _favoritePrimaryColor;

157
Q

What is a common convention for naming private fields in C#?

A

The most common convention is to use camel case with an underscore as a prefix (e.g., _favoritePrimaryColor).

158
Q

How do you add validation logic to a property’s setter in C#?

A

You can add validation logic by implementing custom logic in the set block of the property. For example:
~~~
public string? FavoritePrimaryColor
{
get { return _favoritePrimaryColor; }
set
{
switch (value?.ToLower())
{
case “red”:
case “green”:
case “blue”:
_favoritePrimaryColor = value;
break;
default:
throw new ArgumentException($”{value} is not a primary color.”);
}
}
}
~~~

159
Q

What is a best practice when adding code to a property’s getters and setters?

A

Avoid adding too much code to getters and setters, as it may indicate a design problem. Consider moving logic into private methods.

160
Q

How would you set and retrieve property values in the Program.cs file for FavoriteIceCream and FavoritePrimaryColor?

A

You would set and retrieve values as follows:
~~~
sam.FavoriteIceCream = “Chocolate Fudge”;
WriteLine($”Sam’s favorite ice-cream flavor is {sam.FavoriteIceCream}.”);

sam.FavoritePrimaryColor = “Red”;
WriteLine($”Sam’s favorite primary color is {sam.FavoritePrimaryColor}.”);
~~~

161
Q

How can you limit an enum to a single value in C#?

A

By adding validation in the setter method to throw an exception if multiple values are assigned. For example:
~~~
if (wonderName.Contains(‘,’))
{
throw new ArgumentException(“Favorite ancient wonder can only have a single enum value.”);
}
~~~

162
Q

What exception is thrown when a favorite ancient wonder has more than one enum value?

A

An ArgumentException with the message “Favorite ancient wonder can only have a single enum value.”

163
Q

What C# method can check if an enum value is valid?

A

The Enum.IsDefined() method checks if a value is a valid member of an enum.

164
Q

How does the Enum.IsDefined() method behave when multiple enum values are passed?

A

It returns false for multiple enum values.

165
Q

What operator is used to combine multiple enum values?

A

The bitwise OR (|) operator is used to combine multiple enum values.

166
Q

What is an example of setting multiple enum values in C#?

A

bob.FavoriteAncientWonder = WondersOfTheAncientWorld.StatueOfZeusAtOlympia | WondersOfTheAncientWorld.GreatPyramidOfGiza;

167
Q

What error occurs if you try to set an enum to an invalid value like 128?

A

An ArgumentException is thrown with the message “128 is not a member of the WondersOfTheAncientWorld enum.”

168
Q

What is the purpose of defining indexers in C#?

A

Indexers allow calling code to use array syntax to access a property. For example, accessing individual characters in a string.

169
Q

How can indexers be overloaded in C#?

A

Indexers can be overloaded to accept different types as parameters, such as int or string.

170
Q

How do you define an indexer for getting and setting a child using its index in C#?

A
public Person this[int index]
{
    get { return Children[index]; }
    set { Children[index] = value; }
}
171
Q

How do you define an indexer for getting a child by name in C#?

A
public Person this[string name]
{
    get { return Children.Find(p => p.Name == name); }
}
172
Q

What code can be used to add two children to a person and access them using both indexer syntax and a list?

A
sam.Children.Add(new() { Name = "Charlie", Born = new DateTime(2010, 3, 18) });
sam.Children.Add(new() { Name = "Ella", Born = new DateTime(2020, 12, 24) });

WriteLine($"Sam's first child is {sam.Children[0].Name}.");
WriteLine($"Sam's second child is {sam.Children[1].Name}.");
WriteLine($"Sam's first child is {sam[0].Name}.");
WriteLine($"Sam's second child is {sam[1].Name}.");
WriteLine($"Sam's child named Ella is {sam["Ella"].Age} years old.");
173
Q

What is the output of the code that accesses children using indexers in C#?

A
Sam's first child is Charlie.
Sam's second child is Ella.
Sam's first child is Charlie.
Sam's second child is Ella.
Sam's child named Ella is 3 years old.
174
Q

What is the purpose of pattern matching with objects in C#?

A

Pattern matching allows for testing the properties or types of objects, enabling more concise and readable code through the use of switch expressions.

175
Q

What classes are defined for pattern-matching flight passengers in the example?

A

The classes defined are Passenger, BusinessClassPassenger, FirstClassPassenger, and CoachClassPassenger.

176
Q

How is a switch expression used to calculate the cost of a flight based on passenger type?

A

The switch expression uses pattern matching to evaluate the type of passenger and their properties:
~~~
decimal flightCost = passenger switch
{
FirstClassPassenger p when p.AirMiles > 35_000 => 1_500M,
FirstClassPassenger p when p.AirMiles > 15_000 => 1_750M,
FirstClassPassenger _ => 2_000M,
BusinessClassPassenger _ => 1_000M,
CoachClassPassenger p when p.CarryOnKG < 10.0 => 500M,
CoachClassPassenger _ => 650M,
_ => 800M
};
~~~

177
Q

What does the use of _ signify in a switch expression?

A

The _ represents a wildcard or default pattern match, which can be used to match any object without caring about its properties.

178
Q

What exception is thrown if a flight passenger’s cost doesn’t match any specific case in a switch expression?

A

The default case (_) in a switch expression would provide a fallback value (e.g., $800), so no exception is thrown unless explicitly programmed.

179
Q

What is the output of the code when calculating flight costs for passengers with different properties?

A
Flight costs $2,000.00 for First Class with 1,419 air miles: Suman
Flight costs $1,750.00 for First Class with 16,562 air miles: Lucy
Flight costs $1,000.00 for Business Class: Janice
Flight costs $650.00 for Coach Class with 25.70 KG carry on: Dave
Flight costs $500.00 for Coach Class with 0.00 KG carry on: Amit
180
Q

What improvement to pattern matching was introduced in C# 9 and later regarding discarding local variables?

A

In C# 9 and later, the underscore (_) is no longer needed to discard the local variable when performing type matching.

181
Q

How is a nested switch expression used in C# 9 or later to handle pattern matching for FirstClassPassenger?

A

In C# 9 or later, you can use a nested switch expression to simplify the logic:
~~~
FirstClassPassenger p => p.AirMiles switch
{
> 35_000 => 1_500M,
> 15_000 => 1_750M,
_ => 2_000M
}
~~~

182
Q

How can the relational pattern be combined with the property pattern in C# 9 or later to simplify switch expressions?

A

You can avoid a nested switch expression by using a relational pattern with the property pattern:
~~~
FirstClassPassenger { AirMiles: > 35000 } => 1_500M,
FirstClassPassenger { AirMiles: > 15000 } => 1_750M,
FirstClassPassenger => 2_000M
~~~

183
Q

What is the default branch in a switch expression, and how is it represented?

A

In switch expressions, the underscore (_) represents the default branch.

184
Q

What was the output when the PeopleApp project was run with the updated pattern matching logic for passengers?

A

The output remained the same as before:
~~~
Flight costs $2,000.00 for First Class with 1,419 air miles: Suman
Flight costs $1,750.00 for First Class with 16,562 air miles: Lucy
Flight costs $1,000.00 for Business Class: Janice
Flight costs $650.00 for Coach Class with 25.70 KG carry on: Dave
Flight costs $500.00 for Coach Class with 0.00 KG carry on: Amit
~~~

185
Q

What is the purpose of init-only properties introduced in C# 9?

A

init-only properties allow properties to be set only during object initialization, making them immutable after instantiation.

186
Q

How do you define init-only properties in C#?

A

You define them by using the init keyword in place of set:
public string? FirstName { get; init; }

187
Q

What happens if you try to modify an init-only property after object initialization in C#?

A

You will receive a compile-time error stating that init-only properties can only be assigned during object initialization.

188
Q

What is a record in C# and how does it provide immutability?

A

A record in C# is a type defined using the record keyword that makes the entire object immutable, and comparisons of records are based on their values rather than references.

189
Q

What is non-destructive mutation in C# records, and how is it achieved?

A

Non-destructive mutation allows creating a new record with modified properties without altering the original. This is achieved using the with expression:
ImmutableVehicle repaintedCar = car with { Color = "Grey" };

190
Q

What is the difference between init-only properties and the immutability provided by records in C#?

A

init-only properties allow immutability of individual properties after object initialization, while records make the entire object immutable and use value-based equality.

191
Q

How does the with keyword function in C# 9 for records?

A

The with keyword creates a new record based on an existing one, with specified properties changed:
ImmutableVehicle newCar = car with { Color = "Blue" };

192
Q

How does equality differ between classes and record types in C#?

A

Two instances of a class with the same property values are not considered equal, but two instances of a record with the same property values are considered equal.

193
Q

How is equality for class instances and record instances compared in C#?

A

Class instances are compared by reference (memory address), whereas record instances are compared by value (property values).

194
Q

What output would you expect when comparing two instances of AnimalClass and two instances of AnimalRecord with the same property values?

A
ac1 == ac2: False
ar1 == ar2: True
195
Q

What is a positional record in C# and how is it defined?

A

A positional record in C# allows simplified syntax for defining properties, constructor, and deconstructor. For example:
public record ImmutableAnimal(string Name, string Species);

196
Q

How do you deconstruct a positional record in C#?

A

You can deconstruct a record using its Deconstruct method:
var (name, species) = new ImmutableAnimal(“Oscar”, “Labrador”);

197
Q

What is the output of deconstructing the following record in C#?
~~~
ImmutableAnimal oscar = new(“Oscar”, “Labrador”);
var (who, what) = oscar;
~~~

A

The output is:
~~~
Oscar is a Labrador.
~~~

198
Q

What is a primary constructor in C# 12?

A

A primary constructor in C# 12 is a constructor defined as part of the class definition. It provides a more succinct syntax for initializing class parameters directly within the class declaration.

199
Q

How is a traditional class constructor written compared to a primary constructor in C# 12?

A

In a traditional class, the constructor is defined separately inside the class body:
~~~
public class Headset
{
public Headset(string manufacturer, string productName)
{
// constructor logic
}
}
~~~

In C# 12, a primary constructor can be written as:
public class Headset(string manufacturer, string productName);

200
Q

Do parameters in a primary constructor automatically become public properties in C#?

A

No, parameters in a primary constructor do not automatically become public properties. You need to explicitly define properties and assign them in the constructor body.

201
Q

How do you add properties to a class with a primary constructor in C# 12?

A

You add properties explicitly and assign them using the parameters of the primary constructor:
~~~
public class Headset(string manufacturer, string productName)
{
public string Manufacturer { get; set; } = manufacturer;
public string ProductName { get; set; } = productName;
}
~~~

202
Q

How can you provide a default constructor when using a primary constructor in C# 12?

A

You can define a default parameterless constructor that calls the primary constructor with default values:
public Headset() : this("Microsoft", "HoloLens") { }

203
Q

What is the behavior of instantiating a class with a default constructor and setting values manually?

A

The default constructor can initialize properties with default values, and you can manually change them later using object initializer syntax:
Headset mq = new() { Manufacturer = "Meta", ProductName = "Quest 3" };