Defining Classes, Attributes and Objects
Defining Classes, Attributes, and Objects
Welcome back! Now that you understand the basics of the Program class and the Main function, it's time to take the next step in your C# journey. In this lesson, we will focus on defining our own classes, attributes, and objects, which are core concepts of Object-Oriented Programming (OOP). C# is an OOP language, and this knowledge is crucial as it forms the basis for creating structured and reusable code.
Understanding OOP and its Key Concepts
Object-Oriented Programming (OOP) is a programming paradigm that uses "objects" to design applications and programs. It makes your code more modular, reusable, and easy to maintain. Here's a quick breakdown of its key concepts:
- Class: Think of a class as a blueprint for creating objects. It defines a type and outlines what functionalities that type has.
- Attribute: These are variables defined in a class that hold data about the objects created from the class. For example, an attribute of a Spaceship class might be its name.
- Object: An object is an instance of a class. If the class is a blueprint, the object is the actual creation based on that blueprint. Each object can have different attribute values. For instance, a Spaceship object could have the name "Voyager-1".
What You'll Learn
In this lesson, you'll learn how to define a class, add attributes, and create objects in C#. Classes act as blueprints for objects, attributes store the data for these objects, and objects are instances of these classes.
Here's a simple code example to illustrate this:
By the end of this lesson, you'll know how to define a class, add attributes, and create objects just like we did for the Spaceship class.
Defining Attributes in a Class
An attribute in a class is defined by specifying its data type and name. Let's break down our example to better understand how to define an attribute in a class.
In this code:
publickeyword is used to declare an attribute that can be accessed from outside the class.string?means that thenameattribute can hold either a string value or benull. The?symbol in C# indicates that the type is nullable, meaning the attribute can be set to a string or left asnullby default.nameis the attribute's name, which can be used to store information about the object.
By making an attribute public and possibly nullable (?), you allow for more flexible and accessible data handling within your class instances.
