Classes and Structs:
Classes and structs both are essentially templates from which you can create objects,
Each Objectr has data and methods to manipulate and access that data.The class defines what
data and functionality each particular object(called instance) of that class can contain.
For Example:
If you have a class that repesents a customer ,it might define fields such as
CustomerId,FirstName,LastName,Age,salary,etc..which you will use to hold information about a
particular customer.it might also define functionality that acts upon the data stored in these
fields.you can instantiate an object of this class to represent one specific customer,set the
field values for that instance, and use its funtionality.
Class Customer
{
Public int CustomerID;
public string FirstName;
public String LastName;
}
Structs differ from classes in the way that they are stored inn memory and accessed(Classes
are reference types stored in heap,structs are vlaue type stored on the stock),and in some
of the features(for example structs don't support inheritance).you will tend to use structs
for smaller data types for performance reasons. In term of syntax,structs look very similar
to classes;the main difference is that you use the keyword struct instead of class to declare
them.
Struct Customerstruct
{
Public int CustomerID;
public string FirstName;
public String LastName;
}
For Both Classes and structs, you use the keyword new to declare an instance:This keyword creates
the object and initializes it, in the following example,the default behavior Zero out its fields
Customer cust = new Customer();//works for a class
Customerstruct custstu = new Customerstruct();//works for a structs
we will see what is classmember in next topic.
No comments:
Post a Comment