Classes and Structs
In this chapter you will learn:
What is custom types
We can use classes and structs to build new types. Classes and structs are a data structure that encapsulates a set of data and behaviors. The data and behaviors are the members of the class or struct.
A class or struct type is like a blueprint. After class or struct type declaration we can create instances or objects at run time.
Suppose we create a class called Person
and
variable p
is Person
type, the
p
is said to be an object or instance of
Person
.
We can define multiple instances of the same Person
type,
for example, p1, p2, p3
.
p1, p2, p3
can have different values
in its properties and fields.
A class is a reference type, which means p1
hold
only a reference to the Person
object.
A struct is a value type.
In the following example, Rectangle
is defined
with two members.
An instance (object) of Rectangle
is created in the Main
method,
and the object's methods and properties are accessed by using dot notation.
// Class definition./* ja v a 2 s. c om*/
public class Rectangle
{
public int Width;
public int Height;
}
public class MainClass{
public static void Main(){
Rectangle r = new Rectangle();
r.Width = 5;
}
}
Next chapter...
What you will learn in the next chapter: