Welcome back, C# enthusiast! We're diving into C# classes, focusing on constructors
and class methods
. Picture building a robot: Constructors are the initial settings, and class methods are the commands that enable it to perform actions. Are you ready for a refresher? Let's get started!
A C# class serves as a blueprint for creating objects. Here's a basic class, Robot
:
C#1public class Robot 2{ 3 // Class definition 4} 5 6Robot robotInstance = new Robot();
As of now, this Robot
class is like an empty shell. It exists but doesn't know how to do anything. To make it functional, attributes and methods are needed.
A constructor
is a special method that initializes an object when it is created. In C#, the constructor method has the same name as the class and is called automatically during object creation. It sets up the initial states of the new object.
If you do not define a constructor
method in your class, C# will provide a parameterless constructor automatically.
Here, we upgrade the Robot
class with a constructor
:
C#1public class Robot 2{ 3 public string Name { get; set; } 4 public string Color { get; set; } 5 6 public Robot(string name, string color) 7 { 8 Name = name; 9 Color = color; 10 } 11} 12 13public class Program 14{ 15 public static void Main(string[] args) 16 { 17 Robot robotInstance = new Robot("Robbie", "red"); // Robbie, a red robot, is born! 18 } 19}
In this case, the constructor
method gets automatically called when we create a new Robot
instance, set with Name
and Color
attributes. It's always good practice to use constructors to ensure each instance starts with the correct initial values.
Please note that Name
and this.Name
used in the last unit refer to the same thing. The this
keyword is used to refer to the current instance of the class. However, since there is no ambiguity between the parameter name and the class property Name
here, you don't need to use this
. If the parameter names were the same as the property names, you would need to use this
to distinguish them.
Having one constructor is great, but what if we want more flexibility in setting up our robots? That's where constructor overloading in C# comes into play, allowing you to define multiple constructors with different parameters.
Here's an example of constructor overloading with a constructor initializer:
C#1public class Robot 2{ 3 public string Name { get; set; } 4 public string Color { get; set; } 5 6 // Constructor with explicit color 7 public Robot(string name, string color) 8 { 9 Name = name; 10 Color = color; 11 } 12 13 // Constructor overloading using initializer, defaulting to grey 14 public Robot(string name) : this(name, "grey") 15 { 16 } 17} 18 19public class Program 20{ 21 public static void Main(string[] args) 22 { 23 Robot robotInstance1 = new Robot("Robbie", "red"); // Red Robbie 24 Robot robotInstance2 = new Robot("Bobby"); // Grey Bobby, if no color provided 25 } 26}
The syntax using a constructor initializer allows one constructor to call another constructor within the same class, avoiding code duplication and ensuring consistent initialization. With this approach, when creating a Robot
instance without specifying Color
, it defaults to 'grey'.
Alternatively, you can use a constructor with default parameters, which provides a more straightforward method of setting default values. This approach allows flexibility while keeping the code clean.
Here's how you can define a constructor with a default parameter for Color
:
C#1public class Robot 2{ 3 public string Name { get; set; } 4 public string Color { get; set; } 5 6 // Constructor using default parameter for color 7 public Robot(string name, string color = "grey") 8 { 9 Name = name; 10 Color = color; 11 } 12} 13 14public class Program 15{ 16 public static void Main(string[] args) 17 { 18 Robot robotInstance1 = new Robot("Robbie", "red"); // Red Robbie 19 Robot robotInstance2 = new Robot("Bobby"); // Grey Bobby 20 } 21}
By using default parameters, when creating a Robot
instance without specifying Color
, it defaults to 'grey', similar to constructor overloading, but with a simpler syntax.
Class methods are akin to commands controlling the robot's actions. They provide additional behaviors for our objects.
This Robot
class allows the robots to introduce themselves:
C#1using System; 2 3public class Robot 4{ 5 public string Name { get; set; } 6 public string Color { get; set; } 7 8 public Robot(string name, string color) 9 { 10 Name = name; 11 Color = color; 12 } 13 14 public Robot(string name) : this(name, "grey") 15 { 16 } 17 18 public void SayHello() 19 { 20 Console.WriteLine($"Hello, I am {Name} and I am {Color}."); 21 } 22} 23 24public class Program 25{ 26 public static void Main(string[] args) 27 { 28 Robot robotInstance = new Robot("Robbie", "red"); 29 robotInstance.SayHello(); // "Hello, I am Robbie and I am red." 30 } 31}
The SayHello
method allows our robot instance to interact and even communicate.
Sometimes, you might want to alter the attributes of your class instances or fetch their values. You can accomplish this by creating methods to set or get these attributes.
Here’s how you can add methods to change the Name
and Color
of the robot, as well as retrieve them:
C#1using System; 2 3public class Robot 4{ 5 public string Name { get; set; } 6 public string Color { get; set; } 7 8 public Robot(string name, string color) 9 { 10 Name = name; 11 Color = color; 12 } 13 14 public Robot(string name) : this(name, "grey") 15 { 16 } 17 18 public void SayHello() 19 { 20 Console.WriteLine($"Hello, I am {Name} and I am {Color}."); 21 } 22 23 public void SetName(string newName) 24 { 25 Name = newName; 26 } 27 28 public string GetName() 29 { 30 return Name; 31 } 32 33 public void SetColor(string newColor) 34 { 35 Color = newColor; 36 } 37 38 public string GetColor() 39 { 40 return Color; 41 } 42 43 public void ChangeAttributes(string newName, string newColor) 44 { 45 Name = newName; 46 Color = newColor; 47 } 48 49 public void GreetPerson(string personName) 50 { 51 Console.WriteLine($"Hello {personName}, I am {Name}!"); 52 } 53} 54 55public class Program 56{ 57 public static void Main(string[] args) 58 { 59 Robot robotInstance = new Robot("Robbie", "red"); 60 robotInstance.SayHello(); // "Hello, I am Robbie and I am red." 61 62 robotInstance.SetName("Bobby"); 63 robotInstance.SetColor("blue"); 64 robotInstance.SayHello(); // "Hello, I am Bobby and I am blue." 65 66 Console.WriteLine(robotInstance.GetName()); // "Bobby" 67 Console.WriteLine(robotInstance.GetColor()); // "blue" 68 69 robotInstance.ChangeAttributes("Charlie", "green"); 70 robotInstance.SayHello(); // "Hello, I am Charlie and I am green." 71 72 robotInstance.GreetPerson("Alice"); // "Hello Alice, I am Charlie!" 73 } 74}
The SetName
and SetColor
methods allow changing the Name
and Color
of the robot after it has been created. The GetName
and GetColor
methods enable retrieving these values when needed.
Great job! You've refreshed and deepened your understanding of C# classes, constructors
, and class methods
, and learned how to use constructor overloading for flexibility. Additionally, you saw how to add methods that can update and retrieve class attributes. Now, you can bring more life into your C# classes, making them more versatile and powerful. Next, we'll move on to hands-on tasks where you'll apply these concepts to more complex scenarios. Keep up the good work!