출처 :
http://www.devarticles.com/c/a/c-sharp/ ··· sharp%2FIntroduction to Objects and Classes in C# (Page 1 of 9 )
In
this article Michael introduces us to C#, as well as attempts to
demystify the theory behind "Object and Classes" in OO Programming.
In
this article I will explain some of the concepts behind object-oriented
programming in C#, including objects and classes. To read this article
you should have some basic understanding of the C-Sharp language.
Read
the whole article because there are some concepts you may not fully
understand until you finish the article. And we will revisit all the
concepts more than once when I see it's appropriate in future articles;
so don't worry at all.
Introduction to Objects and Classes in C# - Introduction
(Page 2 of 9 )
OOP
stands for Object-Oriented Programming. OOP is relatively a new way to
program computer applications. In the past, OOP programmers used to
create computer applications using procedural-programming (or
structured-programming). But, when OOP solved a lot of the problems of
the procedural-programming, most programmers and developers began using
OOP languages. In procedural- programming all the program functionality
is written in a few modules of code or maybe one module (depending on
the program). These modules depend on one another and sometimes
changing a line of code requires you to rewrite the whole module again
and maybe the whole program.
In Object-Oriented Programming
programmers write independent parts of a program called classes. Each
class represents a part of the program functionality and these classes
can be assembled to form a program. When you need to change some of the
program functionality all you have to do is to replace the target class
which may contain the problem that needs change. So, OOP applications
are created by the use of classes and these applications can contain
any number of classes. This will get us to discuss the Class and Object
concept.
Classes and objects
You
may find it a little difficult to understand the class and object
story; but, I will try to do my best in explaining it. Actually the
class and object concept is related to each other. Some beginners don't
care about understanding it clearly so I think they will have a hard
time learning C#.
Object-Oriented
concepts take most of their functionality from the real-life concepts.
For example, I will discuss the concept of Classes and Objects of the
world first and then you will understand the computer's Classes and
Objects before I even write anything about it.
Introduction to Objects and Classes in C# - World's Classes and Objects
(Page 3 of 9 )
In
our world we have classes and objects for those classes. Everything in
our world is considered to be an object. For example, people are
objects, animals are objects too, minerals are objects; everything in
the world is an object. Easy, right? But what about classes?
In
our world we have to differentiate between objects that we are living
with. So we must understand that there are classifications (this is how
they get the name and the concepts of the Class) for all of those
objects. For example, I'm an object, David is object too, Maria is
another object. So we are from a people class (or type). I have a dog
called Ricky so it's an object. My friend's dog, Doby, is also an
object so they are from a Dogs class (or type).
A third
example: I have a Pentium 3; this is an object. My friend has a
Pentium 4, so this is another object and they are from a Computers
class (or type). Now I think you understand the concept of the Class
and Object, but let me crystallize it for you. In our world we have
classifications for objects and every object must be from some
classification. So, a Class is a way for describing some properties and
functionalities or behaviors of a group of objects. In other words, the
class is considered to be a template for some objects. So maybe I will
create a class called person which is a template of the functionality
and the properties of persons.
Introduction to Objects and Classes in C# - Programmer’s Classes and Objects
(Page 4 of 9 )
A
C# Class is considered to be the primary building block of the
language. What I mean by the primary building block is that every time
you work with C# you will create classes to form a program. We use
classes as a template to put the properties and functionalities or
behaviors in one building block for a group of objects and after that
we use the template to create the objects we need.
For
example, we need to have persons objects in our program so the first
thing to do here is to create a class called Person that contains all
the functionalities or behaviors and properties of any person and after
that we will use that class (or template) to create as many objects as
we need. Creating an object of a specific class type is called "an
instance of the class". Don't worry if you didn't grasp it 100% and
don't worry if you don't know what the class and object's properties
and functionalities or behaviors are because we are still in the
beginning. Until now I haven’t provided any code examples. So let's
take a brief of what is a class and what is an object:
The
class: A building block that contains the properties and
functionalities that describe some group of objects. We can create a
class Person that contains:
- The properties of any normal person on the earth like: hair color, age, height, weight, eye color.
- The functionalities or behaviors of any normal person on the earth like: drink water, eat, go to the work.
Later we will see how we can implement the functionalities or behaviors and properties.
There
are 2 kinds of classes: The built-it classes that come with the .NET
Framework, called Framework Class Library, and the programmer
defined-classes which we create ourselves.
The
class contains data (in the form of variables and properties) and
behaviors (in the form of methods to process these data). We will
understand this concept later on in the article.
When
we declare a variable in a class we call it member variables or
instance variables. The name instance come from the fact that when we
create an object we instantiate a class to create that object. So
instance of a class means an object of that class and instance variable
means variable that exists in that class.
The
object: It's an object of some classification (or class, or type) and
when you create the object you can specify the properties of that
object. What I mean here is: I, as an object, can have different
properties (hair color, age, height, weight) than you as another
object. For example, I have brown eyes and you have green eyes. When I
create 2 objects I will specify a brown color for my object's eye color
property and I will specify a green color for your object's eye color
property.
So to complete my introduction to classes we must discuss properties and variables.
Introduction to Objects and Classes in C# - Properties and Variables
(Page 5 of 9 )
Variables
declared in a class store the data for each instance. What does this
mean? It means that when you instantiate this class (that is, when you
create an object of this class) the object will allocate memory
locations to store the data of its variables. Let's take an example to
understand it well.
class Person
{
public int Age;
public string HairColor;
}
This
is our simple class which contains 2 variables. Don't worry about
public keyword now because we will talk about it later. Now we will
instantiate this class (that is, when you create an object of this
class).
static void Main(string[] args)
{
Person Michael = new Person();
Person Mary = new Person();
// Specify some values for the instance variables
Michael.Age = 20;
Michael.HairColor = "Brown";
Mary.Age = 25;
Mary.HairColor = "Black";
// print the console's screen some of the variable's values
Console.WriteLine("Michael's age = {0}, and Mary's age = {1}",Michael.Age,
Mary.Age);
Console.ReadLine();
}
So
we begin our Main method by creating 2 objects of type Person. After
creating the 2 objects we initialize the instance variables for object
Michael and then for object Mary. Finally we print some values to the
console. Here, when you create the Michael object, the C# compiler
allocates a memory location for the 2 instance variables to put the
values there. Also, the same thing with the Mary object; the compiler
will create 2 variables in memory for Mary object. So each object now
contains different data. Note that we directly accessed the variables
and we put any values we wanted, right? But wait there is a solution
to this problem. We will use properties.
Introduction to Objects and Classes in C# - Properties
(Page 6 of 9 )
Properties are a way to access the variables of the class in a secure manner. Let's see the same example using properties.
class Person
{
private int age;
private string hairColor;
public int Age
{
get
{
return age;
}
set
{
if(value <= 65 && value >= 18)
{
age = value;
}
else
age = 18;
}
}
public string HairColor
{
get
{
return hairColor;
}
set
{
hairColor = value;
}
}
}
I
made some modifications, but focus on the new 2 properties that I
created. So the property consists of 2 accessors. The get accessor,
responsible of retrieving the variable value, and the set accessor,
responsible of modifying the variable's value. So the get accessor code
is very simple. We just use the keyword return with the variable name
to return its value. So the following code:
get
{
return hairColor;
}
returns the value stored in hairColor.
[Note]
The
keyword value is a reserved keyword by C# (that is, reserved keywords
means that these keywords are owned only by C# and you can't create it
for any other purposes. For example, you can't create a variable called
value .If you did, the C# compiler would generate an error. To make
things easier, Visual Studio.NET will color the reserved keywords in
blue.)
[/Note]
Let's put this code to work and then discuss the set accessor..
Introduction to Objects and Classes in C# - Reworked
(Page 7 of 9 )
static void Main(string[] args)
{
Person Michael = new Person();
Person Mary = new Person();
// Specify some values for the instance variables
Michael.Age = 20;
Michael.HairColor = "Brown";
Mary.Age = 25;
Mary.HairColor = "Black";
// print the console's screen some of the variable's values
Console.WriteLine("Michael's age = {0}, and Mary's age = {1}",Michael.Age,
Mary.Age);
Console.ReadLine();
}
Here
I created the same objects from the last example, except that I used
only properties to access the variable instead of accessing it
directly. Look at the following line of code
Michael.Age = 20;
When
you assign a value to the property like that C# will use the set
accessor. The great thing with the set accessor is that we can control
the assigned value and test it; and maybe change to in some cases. When
you assign a value to a property C# changes the value in a variable and
you can access the variable's value using the reserved keyword value
exactly as I did in the example. Let's see it again here.
set
{
if(value <= 65 && value >= 18)
{
age = value;
}
else
age = 18;
}
Here
in the code I used if statement to test the assigned value because for
some reason I want any object of type Person to be aged between 18 and
65. Here I test the value and if it is in the range then I will simply
store it in the variable age. If it's not in the range I will put 18 as
a value to age.
Introduction to Objects and Classes in C# - Creating Objects and Classes
(Page 8 of 9 )
We create a class by defining it using the keyword class followed by the class name:
class Person
Then
we open a left brace "{" and write our methods and properties. We then
close it with a right brace "}". That's how we create a class. Let's
see how we create an instance of that class.
In the same way as we declare a variable of type int we create an object variable of Person type with some modifications:
int age;
Person Michael = new Person();
In
the first line of code we specified integer variable called age. In the
second line we first specified the type of Object we need to create,
followed by the object's name, followed by a reserved operator called
new. We end by typing the class name again followed by parentheses
"()".
Let's understand it step-by-step.
Specifying the class name at the beginning tells the C# Compiler to
allocate a memory location for that type (the C# compiler knows all the
variables and properties and methods of the class so it will allocate
the right amount of memory). Then we followed the class name by our
object variable name that we want it to go by. The rest of the code "=
new Person();" calls the object's constructor. We will talk about
constructors later but for now understand that the constructor is a way
to initialize your object's variable while you are. For example, the
Michael object we created in the last section can be written as
following :
Person Michael = new Person(20, "Brown");
Here
I specified the variable's values in the parameter list so I
initialized the variables while creating the object. But for this code
to work we will need to specify the constructor in the Person class --
I will not do that yet as constructors will come in a later article.
Introduction to Objects and Classes in C# - Conclusion
(Page 9 of 9 )
In
this article, I gave you a concise introduction to classes and objects.
I will complete the discussion in my next article, as well as discuss
constructors and building block scope. I hope you’ve learned something
new thing from this first article.
Introduction to Objects and Classes in C#, Part 2
(Page 1 of 4 )
After I wrote the article named Introduction to Objects and Classes in C#, I got a lot of e-mail
messages asking me to create a series of articles about Objects and
Classes. Actually this was a few months back (sorry for being late),
but I'm here again with part two. In Part one, I explained the concepts
behinds Objects and Classes but I didn't discuss why Object Oriented
Programming (OOP) uses the Object and Class technique. Today, I will
discuss the advantage of Objects and Classes with more details on how
to understand your problems and develop your Objects for your solution.Because
this series targets the true beginners, I will not use any technical
expressions and I will prefer to explain concepts by examples. I
presume that readers have a basic knowledge of C# (control the flow of
the program, using methods and arrays, namespaces & assemblies).
The
first thing that you should know about C# programming is that it uses
the Class to include the data (in part one, I said that data can be
stored in instance variables in the class) and methods to process that
data. Think about it in the next example:
class Test
{
public int Add(int x, int y)
{
return x + y;
}
}
The
class Test contains a method called Add (which add to integers and
return the result) is a good example for what we are talking about. I
said that the Class includes data and there are methods to process that
data, here the class test includes the method Add()
which takes two integer numbers to add them and this is the
functionality of the method. The application that will use the Test
class can be something like the following:
public
class Class1
{
public Class1()
{
Test t1 = new Test();
Console.WriteLine(t1.Add(5,4));
}
}
The
concept of Objects & Classes helps you hide your code
implementation from the user of your class. In other words, if you
develop a class for your friend to use, he doesn't have to know how you
created the methods of that class in order to use it; he'll just need
to know how to use it, and what functionality is offered by your class
members. The point here is that you don't have to know how another
developer developed a certain class; you just have to know how to
interface with it. And I said in the first part, when you develop
programs with C# you will develop classes. Note that this is not like C
programming, where the programming primary building block was the
function (or methods, in C#). Finally, remember that C# defines other
types like structures, enumerations. We'll learn about these in future
articles.
In C programming language, programmers develop
functions to form their applications. These functions contain the code
of the program. The problem is that in large programs, if you have to
modify just one line of code you may have to modify many functions to
fit in the new modifications. (In procedural languages, functions
depend on each other.) But in C#, we write classes as our primary
building blocks, and because classes hide their code implementation --
and only the methods of these classes are accessible to the
applications that use them -- if we must change something inside the
class, we will do it without changing the code of the applications that
uses our classes.
Introduction to Objects and Classes in C#, Part 2 - Comments
(Page 2 of 4 )
When
you write applications in C# try to use comments to describe exactly
how your application performs and why; try to make your
application easy to understand and easy to maintain. Think about it
this way: if you were to come back to your application five years after
you wrote it, would you know what every line of code meant and did?
What if someone was developing an application and they were trying
to read through your code? Without documentation, this is difficult
even for the most experienced programmers.
I think that you want to know more about classes so let's write a class and then discuss new concepts.
The Person Class
Here's a simple class called Person
class Person
{
// These are 3 private instance variables
// for now just consider them instance members of
// that class
private string firstName;
private string lastName;
private int age;
// This called the default constructor
public Person()
{
firstName = "Unknown";
lastName = "Unknown";
age = 0;
}
// This also a Constructor and we will understand
// the use of it and why we create constructors
public Person(string fName, string lName, int pAge)
{
firstName = fName;
lastName = lName;
age = pAge;
}
// This is a method just writes a string to the console.
// this string consists of the 3 variables and
// displaying the information about the person.
public void PersonInfo()
{
Console.WriteLine("First Name = {0}, Last Name = {1} and his age = {2}",
firstName, lastName, age);
}
}
Let's break this down:
You're probably curious about private string firstName, private string lastName, and private int age. These are called instance variables,
and as you know from the first part of that article, when you create
objects from a given class (for example, the person class) you create
an instance of that class. That's why we call the variables declared
the body of the class (but not inside any method of that class) an
instance variable. When you create an objects of that class C# compiler
will allocate separate memory locations for the instance variables of
each object. Thus, the object named Michael (of type Person) will contain its own values for these instance members, as will the object Prakhar (of type Person).
You can say that the consumer application (the application that will
use your class) will provide the values of these instance variables for
each object created of that type.
NOTE About the keywords private and public in the class, they called access modifier keywords.
When developing C# class you will use the access modifier keywords to
specify the scope of the member. Each instance variable, method, or any
other type you create inside a class called a member. C# gives you the
power to specify the scope of the member using these access modifiers.
Introduction to Objects and Classes in C#, Part 2 - What's a Scope?
(Page 3 of 4 )
Simply,
the scope of a type (a variable, a method, or a class) is where you can
use that type in your program. In other words, the scope defines the
area of the program where that type can be accessible and referenced.
When you declare a variable inside a block of code (like a method or an if statement structure), it will have a local scope, and it will be called a local-variable. Local scope means that you can't refer to that variable outside that block of code. Consider the next example.
class Test
{
public void Test1()
{
int x = 0;
// some code goes here that uses the x variable
}
public void Test2()
{
Console.WriteLine(x);
}
}
Try to instantiate this class and you will get a compile-time error inside method Test2() telling you that the name x doesn't exist and that's because x is a local variable to the method Test1() and method Test2() doesn't know anything about it. So x has a local score to method Test1() only. Consider the next example.
class Test
{
public void Test1()
{
int x = 0;
if(x == 0)
{
Console.WriteLine("x equal to 0");
}
}
}
Here, the method Test1() declares a local variable x (now x
has a local-scope to the method). Try to instance this class and
compile the code. It will work! Some beginners think that because I
said that x has a local scope to method Test1()
it will not be referenced from nested block (like the one we have here,
the If statement) but that's not true because any nested block inside Test1() method can refer x because x is local for the method and its all blocks of code.
NOTE There are 2 kinds of scopes: block scope (the one that we just finished), and a class scope (which we will talk about later in this article). Now, about the keywords private and public
in the class person, you can use these access modifier keywords to
define the scope of your variables, methods, or even your classes.
There are other access modifiers but I will talk about them in a later
article when I will explain the concepts of inheritance.
Instance variables declared using the access modifier keyword private will be accessible to the methods between the opening left brace "{" and the closing right brace "}"
(which define the body of the class) only. In other words, when you
declare an instance variable like in the following example:
public
class Class2
{
private int x;
}
public class Class3
{
void testing()
{
x == 100;
}
}
In this example, you will get a compile-time error telling you that you that the name X doesn't exist inside the Class3. Using the keyword private, you explicitly tell the compiler "Don't show this member to any other class." (So you are hiding it inside the class.)
Introduction to Objects and Classes in C#, Part 2 - Private Members Only?
(Page 4 of 4 )
What about objects of that class? Can they access the members declared as private?
In short, no, the objects of this class will not see
the private member, but it will have it's own copy because as we said
before the class is just a template for the contents of its object. I
prefer to discuss it using an example:
public
class Class2
{
private int x = 100;
}
And then I will instance 2 objects of that class inside the Main method
static void Main
(string[] args)
{
Class2 c2 = new Class2();
Class2 c3 = new Class2();
// Now Let's check if we can see
// x inside any of these objects
c2.
}
c2 and c3 are objects of type Class2() but look what happened when I typed the "." operator (which will get us all the accessible members of that class).

There is no x
here because it's private to the class. You may wonder why this feature
exists. Sometimes you need to hide some values inside the class (ie.
you don't want other classes or objects of that class to see these
values), maybe because it's complex information, or it's private to
your work, or the developers that will use your class (after it's
compiled) will simply not benefit if they saw these variables or
methods.
You can use the access modifier keyword public
while you declare your variables to specify that you want your variable
to be accessed by the other classes or any objects of this class. let's
revise the the x variable in Class2 and check if we can see it or not (from objects of this class or other classes).
public
class Class2
{
public int x = 100;
}
Now let's see the result:

Oh, yes we can see the x variable now because we made it public. And I will talk about Class Scope in a later article. For now, just play around with scopes. I think you'll have a lot of fun with these.
Leave your greetings.