Methods and Classes Flashcards
How do you set a default value for a parameter in a method?
Set the parameter equal to something in the parenthesis.
static void main(string greeting = “Hello”)
{
Console.WriteLine(greeting);
}
What are Named Arguments?
Named arguments are a way to create parameters in a method where the order of the params doesn’t matter. You use the key : value syntax for this.
static void MyMethod(string child1, string child2, string child3)
{
Console.WriteLine(“The youngest child is: “ + child3);
}
static void Main(string[] args)
{
MyMethod(child3: “John”, child1: “Liam”, child2: “Liam”);
}
You can also specify which param to call.
static void Main(string[] args)
{
MyMethod(“child3”);
}
What is Method Overloading?
Method Overloading is where multiple methods can have the same name with different parameters. This allows the method to behave differently based on the arugments used when it’s called.
What is a Constructor?
A special method used to initialize objects. The advantage of a constructor, is that it is called when an object of a class is created. It can be used to set initial values for fields.
The constructor name must match the class name, true or false?
True. The constructor also doesn’t have a return type. All classes have a constructor by default. If you don’t create one, the language will create one for you, but you won’t be able to initialize values.
What are the four Access Modifiers?
Public, Private, Protected, and Internal.
What does the Public Access Modifier do?
Makes the data accessible to all classes.
What does the Private Access Modifier do?
Makes the code accessible only inside of the class.
What does the Protected Access Modifier do?
Makes the code accessible only inside of the class and any class derived from it.
What does the Internal Access Modifier do?
The code is only accessible within its own assembly, but not from another assembly.
What are the two combinations of Access Modifiers
Protected internal and private protected
What is the default Access Modifier?
Private
What keyword do you use if you don’t want other classes to inherit from a class?
Sealed
sealed class Vehicle { ... }
class Car : Vehicle { ... }
Error message: ‘Car’: cannot derive from sealed type ‘Vehicle’
What keyword is used on a base class method to allow it to be overridden?
Virtual
public virtual void animalSound()
{
Console.WriteLine(“The animal makes a sound”);
}
You can also use the abstract keyword.
What keyword is used on a derived class method to allow it to be overridden?
Override
public override void animalSound()
{
Console.WriteLine(“The dog says: bow wow”);
}