Tuesday, February 16, 2010

C# – Static Members


INTRODUCTION:

The object oriented programming will give the impression very unnatural to a programmer with a lot of procedural programming experience. In Object Oriented programming Encapsulation is the first pace. Encapsulation is the procedure of covering up of data and functions into a single unit (called class). An encapsulated object is often called an abstract data type. In this article let us see about it in a detailed manner.

NEED FOR ENCAPSULATION:

The need of encapsulation is to protect or prevent the code (data) from accidental corruption due to the sillylittle errors that we are all prone to make. In Object oriented programming data is treated as a critical element in the program development and data is packed closely to the functions that operate on it and protects it from accidental modification from outside functions.

Encapsulation provides a way to protect data from accidental corruption. Rather than defining the data in the form of public, we can declare those fields as private. The Private data are manipulated indirectly by two ways. Let us see some example programs inC# to demonstrate Encapsulation by those two methods. The first methodis using a pair of conventional accessor and mutator methods. Another one method is using a named property. Whatever be the method our aim is to use the data with out any damage or change.

ENCAPSULATION USING ACCESSORS AND MUTATORS:

Let us see an example of Department class. Tomanipulate the data in that class (String departname) we define anaccessor (get method) and mutator (set method).

using system;
public class Department
{
private string departname;
…….

// Accessor.
public string GetDepartname()
{
return departname;
}

// Mutator.
public void SetDepartname( string a)
{
departname=a;
}

}

Like the above way we can protect the privatedata from the outside world. Here we use two separate methods to assignand get the required data.

public static int Main(string[] args)
{
Department d = new Department();
d.SetDepartname("ELECTRONICS");
Console.WriteLine("The Department is :"+d.GetDepartname());
return 0;
}

In the above example we can't access theprivate data departname from an object instance. We manipulate the dataonly using those two methods.

ENCAPSULATION USING PROPERTIES:

Properties are a new language featureintroduced with C#. Only a few languages support this property.Properties in C# helps in protect a field in a class by reading andwriting to it. The first method itself is good but Encapsulation can beaccomplished much smoother with properties.Now let's see an example.

using system;
public class Department
{
private string departname;
public string Departname
{
get
{
return departname;
}
set
{
departname=value;
}
}
}
public class Departmentmain
{
public static int Main(string[] args)
{
Department d= new Department();
d.departname="Communication";
Console.WriteLine("The Department is :{0}",d.Departname);
return 0;
}
}

From the above example we see the usage ofEncapsulation by using properties. The property has two accessor getand set. The get accessor returns the value of the some property field.The set accessor sets the value of the some property field with thecontents of "value�. Properties can be made read-only. This isaccomplished by having only a get accessor in the propertyimplementation.

READ ONLY PROPERTY:

using system;
public class ReadDepartment
{
private string departname;
public ReadDepartment(string avalue)
{
departname=avalue;
}
public string Departname
{
get
{
return departname;
}
}
}
public class ReadDepartmain
{
public static int Main(string[] args)
{
ReadDepartment d= new ReadDepartment("COMPUTERSCIENCE");
Console.WriteLine("The Department is: {0}",d.Departname);
return 0;
}
}

In the above example we see how to implement aread-only property. The class ReadDepartment has a Departname propertythat only implements a get accessor. It leaves out the set accessor.This particular class has a constructor, which accepts a stringparameter. The Main method of the ReadDepartmain class creates a newobject named d. The instantiation of the d object uses the constructorof the ReadDepartment that takes a string parameter. Since the aboveprogram is read-only, we cannot set the value to the field departnameand we only read or get the value of the data from the field.Properties can be made also Write-only. This is accomplished by havingonly a set accessor in the property implementation.

WRITE ONLY PROPERTY:

using system;
public class WriteDepartment
{
private string departname;

public string Departname
{
set
{
departname=value;
Console.WriteLine("The Department is :{0}",departname);
}
}
}
public class WriteDepartmain
{
public static int Main(string[] args)
{
WriteDepartment d= new WriteDepartment();
d.departname="COMPUTERSCIENCE";
return 0;
}
}

In the above example we see how to implement aWrite-only property. The class WriteDepartment has now has a Departnameproperty that only implements a set accessor. It leaves out the getaccessor. The set accessor method is varied a little by it prints thevalue of the departname after it is assigned.

Conclusion:

The Encapsulation is the first footsteptowards the object-oriented programming. This article gives you alittle bit information about Encapsulation. Using accessor and mutatormethods we can make encapsulation. Another one method is using a namedproperty. The benefit of properties is that the users of your objectsare able to manipulate the internal data point using a single nameditem.

Related Articles :

C# Encapsulation

INTRODUCTION:

The object oriented programming will give theimpression very unnatural to a programmer with a lot of proceduralprogramming experience. In Object Oriented programming Encapsulation isthe first pace. Encapsulation is the procedure of covering up of dataand functions into a single unit (called class). An encapsulated objectis often called an abstract data type. In this article let us see aboutit in a detailed manner.

NEED FOR ENCAPSULATION:

The need of encapsulation is to protect orprevent the code (data) from accidental corruption due to the sillylittle errors that we are all prone to make. In Object orientedprogramming data is treated as a critical element in the programdevelopment and data is packed closely to the functions that operate onit and protects it from accidental modification from outside functions.

Encapsulation provides a way to protect datafrom accidental corruption. Rather than defining the data in the formof public, we can declare those fields as private. The Private data aremanipulated indirectly by two ways. Let us see some example programs inC# to demonstrate Encapsulation by those two methods. The first methodis using a pair of conventional accessor and mutator methods. Anotherone method is using a named property. Whatever be the method our aim isto use the data with out any damage or change.

ENCAPSULATION USING ACCESSORS AND MUTATORS:

Let us see an example of Department class. Tomanipulate the data in that class (String departname) we define anaccessor (get method) and mutator (set method).

using system;
public class Department
{
private string departname;
…….

// Accessor.
public string GetDepartname()
{
return departname;
}

// Mutator.
public void SetDepartname( string a)
{
departname=a;
}

}

Like the above way we can protect the privatedata from the outside world. Here we use two separate methods to assignand get the required data.

public static int Main(string[] args)
{
Department d = new Department();
d.SetDepartname("ELECTRONICS");
Console.WriteLine("The Department is :"+d.GetDepartname());
return 0;
}

In the above example we can't access theprivate data departname from an object instance. We manipulate the dataonly using those two methods.

ENCAPSULATION USING PROPERTIES:

Properties are a new language featureintroduced with C#. Only a few languages support this property.Properties in C# helps in protect a field in a class by reading andwriting to it. The first method itself is good but Encapsulation can beaccomplished much smoother with properties.Now let's see an example.

using system;
public class Department
{
private string departname;
public string Departname
{
get
{
return departname;
}
set
{
departname=value;
}
}
}
public class Departmentmain
{
public static int Main(string[] args)
{
Department d= new Department();
d.departname="Communication";
Console.WriteLine("The Department is :{0}",d.Departname);
return 0;
}
}

From the above example we see the usage ofEncapsulation by using properties. The property has two accessor getand set. The get accessor returns the value of the some property field.The set accessor sets the value of the some property field with thecontents of "value�. Properties can be made read-only. This isaccomplished by having only a get accessor in the propertyimplementation.

READ ONLY PROPERTY:

using system;
public class ReadDepartment
{
private string departname;
public ReadDepartment(string avalue)
{
departname=avalue;
}
public string Departname
{
get
{
return departname;
}
}
}
public class ReadDepartmain
{
public static int Main(string[] args)
{
ReadDepartment d= new ReadDepartment("COMPUTERSCIENCE");
Console.WriteLine("The Department is: {0}",d.Departname);
return 0;
}
}

In the above example we see how to implement aread-only property. The class ReadDepartment has a Departname propertythat only implements a get accessor. It leaves out the set accessor.This particular class has a constructor, which accepts a stringparameter. The Main method of the ReadDepartmain class creates a newobject named d. The instantiation of the d object uses the constructorof the ReadDepartment that takes a string parameter. Since the aboveprogram is read-only, we cannot set the value to the field departnameand we only read or get the value of the data from the field.Properties can be made also Write-only. This is accomplished by havingonly a set accessor in the property implementation.

WRITE ONLY PROPERTY:

using system;
public class WriteDepartment
{
private string departname;

public string Departname
{
set
{
departname=value;
Console.WriteLine("The Department is :{0}",departname);
}
}
}
public class WriteDepartmain
{
public static int Main(string[] args)
{
WriteDepartment d= new WriteDepartment();
d.departname="COMPUTERSCIENCE";
return 0;
}
}

In the above example we see how to implement aWrite-only property. The class WriteDepartment has now has a Departnameproperty that only implements a set accessor. It leaves out the getaccessor. The set accessor method is varied a little by it prints thevalue of the departname after it is assigned.

Conclusion:

The Encapsulation is the first footsteptowards the object-oriented programming. This article gives you alittle bit information about Encapsulation. Using accessor and mutatormethods we can make encapsulation. Another one method is using a namedproperty. The benefit of properties is that the users of your objectsare able to manipulate the internal data point using a single nameditem.

Related Articles :

C# Interface Implementation

Interface implementation can be confusing…

I see a feature in C# that can be very confusing. In theexample below we have a class (Test) that implements 2 interfaces(I1 and I2). So the logic says that we should have implementations in the classTest for both MyFunction() methods from I1 and I2. BUT!As you see in the example below everything works fine with only 1 implementation.This is not as correct as we expect, because we can't be sure which of the two interfacesis implemented in the MyFunction method in class Test.So the solution is in another example (EXAMPLE2).In Example2 MyFunction() is implemented in class Test for each interface, by using a different method. (I1.MyFunction() -> for I1, I2.MyFunction() -> for I2).So now everything is clear, isn't it?

//EXAMPLE 1
using System;

namespace PavelTsekov
{
interface I1
{
void MyFunction();
}
interface I2
{
void MyFunction();
}
class Test : I1,I2
{
public void MyFunction()
{
Console.WriteLine("Guess which interface I represent???!");
}
}
class AppClass
{
public static void Main(string[] args)
{
Test t=new Test();
I1 i1=(I1)t;
i1.MyFunction();
I2 i2=(I2)t;
i2.MyFunction();
}
}
}

//EXAMPLE 2
using System;

namespace PavelTsekov
{
interface I1
{
void MyFunction();
}
interface I2
{
void MyFunction();
}
class Test : I1,I2
{
void I1.MyFunction()
{
Console.WriteLine("Now I can say this here is I1 implemented!");
}
void I2.MyFunction()
{
Console.WriteLine("Now I can say this here is I2 implemented!");
}
}
class AppClass
{
public static void Main(string[] args)
{
Test t=new Test();
I1 i1=(I1)t;
i1.MyFunction();
I2 i2=(I2)t;
i2.MyFunction();
}
}
}

Related Articles :

Is Object Class, the root of all hierarchies?

Introduction
This might come as a surprise for many, to see me doubting theinformation presented in almost .NET books even MSDN library but as wedelve deeper into this topic, you will find yourself in the samepredicament as I am now.

What is an Object class?
For those who arenew to .NET, according to MSDN library – "Object is the ultimatesuperclass of all classes in the .NET Framework; it is the root of thetype hierarchy."

This is the class declaration of the object class
[Serializable]
[ClassInterface(ClassInterfaceType.AutoDual)]
public class object

All the classes are required to inherit fromthis Object class but they need not declare inheritance from itexplicitly as it is taken care internally. While all classes inheritfrom it, it doesn't inherit from any super class or interface.

So what's the problem?
This I will explain with a help of an example.
Let's define a class called Foo

Class Foo
{
void show() {}
static void main(string[] args)
{
Foo f=new Foo();
}
}

If you have Visual Studio IDE or any othereditor which supports intellisense, when you type f. you will get thefollowing methods
1. Equals
2. GetHashCode
3. ToString
4. GetType
5. show

Even though you have defined only one method show since Foo implicitly inherits from Object it gets the other four methods.Let's now define an interface called IFoo and make Foo class inherit from it.

Interface IFoo
{
void Ishow();
}
class Foo:IFoo
{
void show(){}
void IFoo.Ishow(){}
static void main(string[] args)
{
Foo f=new Foo();
IFoo ifoo=f;
}
}

Since we have inherited from IFoo, we need toimplement the Ishow method. When we type ifoo.show(), we get a compiletime error saying that the interface doesn't contain a definition forshow method. This is correct since an interface is allowed to accessonly methods declared by it even though the object it might bereferring has other methods.

The problem arises now when we typeifoo.equals(f), ideally this should give a compile time error (notruntime error) it is not declared by IFoo interface or none of itssuper interface but it doesn't. Nor does it give a compile time errorfor using any of the methods of Object class.

This is definitely a discrepancy from the factthat an interface is allowed to access only methods declared by it. Aninterface for sure can't inherit from a class so how then can weexplain for the four methods of Object which are available to anyinterface. The only possible solution can be that there must be a superinterface like IObject as declared below:

Interface IObject
{
public virtual bool equals(object);
public virtual int getHashCode();
public Type getType();
public virtual string toString();
}

and the Object class must have inherited fromthis interface and also that this IObject must be the super interfaceof all the interfaces just like Object is to other classes.

Conclusion
This is one of the issues whichMicrosoft should clarify so that the programmers can have a betterunderstanding of the language.

Name:C.Prashanth
Email Id:seeprash@hotmail.com
I am a MSc Software Engg student doing my final semester project atIntel Technologies, India. I am a fanatic follower of Indian cricketteam and try not to miss any match even if it means bunking college andoffice. I love reading War novels and listening to A.R.Rahman music.

Related Articles :

C# Class Inheritance

This Console-based C# code calculates theArea, perimeter, surface area and volume of the following polygons:square, rechtangle, parellelogram, trapezoid, triangle, circle, cube,prism (both rechtangular and triangular base), cylinder, cone, sphere,pyramid and rhombus. All the user does is to input the polygon'sdimensions and the code will produce the polygon's attributes.

polygons.cs

author : Martin Raphael.K
// email : mrkraj@officetiger.com
// Date : November 02, 2001

// This is the sample code for inheritence

// new is the keyword which is used to override the base(Parent) class
//members base is the keyword whichs is equal to super in java
using System;
public class Base
{
public string str;
public Base()
{
Console.WriteLine("Base class Constructor");
}
~Base()
{
Console.WriteLine("Base class Destructor");
}
public void getData()
{
Console.WriteLine("Base class GetData");
}
}
public class Derived:Base
{
public new string str;

public Derived()
{
Console.WriteLine("Derived class Constructor");
}
~Derived()
{
Console.WriteLine("Derived class Destructor");
}
public new void getData()
{
base.getData();
Console.WriteLine("Derived class GetData");
}
public void getValues()
{
base.str=Console.ReadLine();
this.str=Console.ReadLine();
}
public void printValues()
{
Console.WriteLine("Base class Str "+base.str);
Console.WriteLine("Derived class Str "+this.str);
}
}

class InheritenceDemo
{
public static void Main(string[] a)
{
Derived d=new Derived();
d.getData();
d.getValues();
d.printValues();
Console.WriteLine("———–");
// this is used to get the Base class getData Method
((Base)d).getData();
}
}

// send a feedback to mrkraj@officetiger.com


Related Articles :

Explaining C# Abstraction, Inheritence and Polymorphism

Far too often, fundamental programming concepts like inheritance and polymorphism are taught using vague examples, like class "AA" and class "BB". Let's get away from that; they're far too abstract to offer a proper explanation. We'll use a workshop as our example instead.

Say you have a program to simulate a workshop, and you want to create a class for each possible tool you can use… hammers, power saws, screwdrivers, etc. Pretty much every tool class you create is going to have common methods, like Use() and PutAway(), regardless of what it actually is. Inheritance allows you to enforce this common ground between tools, and reap some very useful benefits in the process. Take the following "base" class:

public abstract class Tool()
{

private double _price;
public double GetPrice()
{
return _price;
}

public abstract void Use();
public abstract void PutAway();

}

This class doesn't do much of anything on it's own, but it provides a common interface for all of the other tools you create.

Every class that inherits from Tool will automatically have a _price, a method called "GetPrice()", and two other methods called Use() and PutAway(). Because we've already written code for GetPrice(), any other Tool class we write can take advantage of it right away.

Use() and PutAway() are a little different. Because we've declared Use() and PutAway() as abstract methods, any class we write that inherits from Tool [i]must[/i] have its own Use() and PutAway() methods. You might ask, "then why bother putting them in the base Tool class in the first place, if you have to rewrite them in all the inherited classes, anyway"? The reason is because these abstract methods [i]guarantee[/i] to our program that any tool it ever deals with will have these methods, 100% certain. We'll see the benefits of this in a minute, but first let's take a quick look at two classes that inherit from Tool (in place of specific code, I'll just add some comments):

public class ScrewDriver: Tool
{

public override void Use()
{
// Insert into screw head and rotate
}

public override void PutAway()
{
// Find correct drawer in toolbench and place inside
}

}

public class PowerSaw: Tool
{

public override void Use()
{
// Flip "on" switch and apply blade to wood surface
}

public override void PutAway()
{
// Flip "off" switch and place on shelf
}

public void ReplaceBatteries()
{
// Remove old batteries, and insert new ones
}

}

Both ScrewDriver and PowerSaw inherit the Use() and PutAway() methods from Tool, but in addition to this they can implement their own unique methods, as well. For example, PowerSaw has a ReplaceBatteries() method, which would be pointless on a screwdriver, but important on a power tool. And that's a critical point: that's why we didn't put a ReplaceBatteries() method in the tool class… because not [i]every[/i] tool needs a ReplaceBatteries() method. Instead, we placed it in the class that would actually need it. Use() and PutAway(), however, are needed by every tool, and so those methods are in the base class.

Note also that, although you can't see it, both ScrewDriver and PowerSaw also have _price and GetPrice(), because they inherited it from "Tool". For example, the following code is, in theory, perfectly legal:

ScrewDriver myScrewDriver;
myScrewDriver.GetPrice();

What about Use() and PutAway()? Those are actually written in ScrewDriver and PowerSaw, so why do we even care that they're included in Tool? For one thing, it guarantees that you won't forget to add those methods to your inherited classes. For another thing, you can do stuff like this:

Tool[] myArrayOfTools = new Tool[2];
tool[0] = new ScrewDriver();
tool[1] = new PowerSaw();

foreach( Tool myTool in myArrayOfTools )
{
myTool.Use();
myTool.PutAway();
}

And that will be perfectly legal, even though element 0 and element 1 in that array are totally different types! One is a ScrewDriver, and one is a PowerSaw, but because they are both tools, we can call their Use() and PutAway() methods regardless of their specific type.

A few closing points…

1) The "abstract" in "public abstract class Tool()" just means that we can't create instances of our Tool class… which is good, because the actual base Tool class doesn't do anything. We don't want people creating copies of it by accident, they should stick to ScrewDrivers and PowerSaws that can actually do stuff.

2) If we want to write code for Use() in the base class, but still allow it to be overridden by an inheritence class, use "virtual" instead of "abstract":

public virtual void Use()
{
// Generic instructions for using a tool
}

Be aware that, although all inherited classes still have access to virtual methods, they are not required to override them.

3) You don't have to use only one base class. You could create two additional base classes, PowerTool and HandTool that inherit from Tool, and then have your specific tools inherit from either PowerTool or HandTool. PowerTool would have specific methods that all power tools need, and HandTool would have specific methods that all hand tools need. Think of inheritance as a family tree, where in this case, "Tool" is the trunk, "PowerTool" and "HandTool" are both branches, and "ScrewDriver" and "PowerSaw" are twigs.

4) For the record, the ability to use all inherited tools as a normal tool (ie, using a ScrewDriver as a Tool), is called "polymorphism".

5) There are also some really neat things called "Interfaces", which you may want to look into once you're comfortable with inheritance.

Objects & Classes in C#

In this article we will understand some of the concepts of object-oriented programming in C# like objects and classes. To read this article you must have C# programming basics.

NOTE: read the whole article because there aresome concepts you may will not get the best of it until you finish the article.And we will revisit all the concepts more than one time when I see it’sappropriate in future articles so don’t worry at all.

Introduction:

OOP stands for Object-Oriented Programming. OOP isrelatively a new way to program computer applications. Before OOP programmersused to creating computer applications using procedural-programming (orstructure-programming) but when OOP solved a lot of the problems of theprocedural-programming so almost all of the programmers and developers beganusing OOP languages. In procedural- programming all the program functionalitywritten in a few modules of code or maybe one module (depending on the program)and these modules depend on one another and maybe if you change a line of codeyou will have to rewrite the whole module again and maybe the whole program butin Object-Oriented Programming programmers write independent parts of a programcalled classes each class represent a part of the program functionality andthese classes can be assembled to form a program and when you need to changesome of the program functionality all what you have to do is to replace thetarget class which may contain a problem. So in OOP applications create by theuse of classes and these applications can contain any number of classes. Thatwill get us to discuss the Class and Object concept.

Classes and objects:

You may find it not easy to understand the class and objectstory but I will try to do my best explaining it. Actually the class and objectconcept is related to each other and some beginners don’t care aboutunderstanding it clear so I think they will have a hard times learning C#.

Object-Oriented concept takes the most of its functionalityfrom the real-life concepts. For example, I will discuss the concept of Classesand Objects of the world first and then you will understand the computer’sClasses and Objects before I even write anything about it.

World’s Classes and Objects:

In our world we have a classes and objects for thoseclasses. Everything in our world considered to be an object. For example,people are objects, animals are objects too, minerals are objects, everythingin the world are objects. Easy right ? but what about classes. In our world wehave to differentiate between objects that we are living with. So we mustunderstand that there are a classifications (this is how they get the nameand the concepts of the Class) for all of those objects. For example, I’man object, David is object too, Maria is another object so we are from apeople class (or type). I have a dog called Ricky so it’s an object, Myfriend’s dog called Doby is also an object so they are from a Dogs class (ortype). A third example, I have a computer Pentium III this is object, Myfriend have a computer Pentium IIII so this is another object and they are froma Computers class (or type). Now I think you got the concept of theClass and Object but let me crystallize it for you. In our world we have aclassifications for objects and every object must be from some classification.so a Class is a way for describing some properties and functionalities orbehaviors of a group of objects. In other words, The class considered to be atemplate for some objects. So maybe I will create a class called person so thisis a template of the functionality and the properties of persons. I explainedit by more than a way so wait until you see the first example and I think youwill grasp it completely.

Computer’s Classes and Objects:

Computer’s Classes discussion is similar to what you graspfrom the last section with some modifications to become computerized.

A C# Class Considered being the primary building block ofthe language. What I mean by the primary building block of the language is thatevery time you work with C# you will create Classes to form a program. We useClasses as a template to put the properties and functionalities or behaviors inone building block for some group of objects and after that we use thattemplate to create the objects we need. For example, We need to have personsobjects in our program so the first thing to do here is to create a Classcalled Person that contains all the functionalities or behaviors and propertiesof any person and after that we will use that Class or template to create asmany objects as we need. Creating object of a specific class type called”instance of the class”. Don’t worry if you didn’t grasp it 100% anddon’t worry if you don’t know what’s the Class and Object’s properties andfunctionalities or behaviors because we still in the beginning and until now Ididn’t give any code examples. So let’s take a brief of what’s the Class andwhat’s an object ?

The Class : Is abuilding block that contains the properties and functionalities that
describesome group of objects, We can create a class Person that contains:

1- The properties of any normal person on the earth like :Hair Color, Age, Height, Weight, Eyes Color.

2- The functionalities or behaviors of any normal person onthe earth like : Drink water, Eat, Go to the work and later we will see how wecan implement the functionalities or behaviors and properties.

There are 2 kinds of classes : The built-it classes thatcome with the .NET Framework and called Framework Class Library. And theprogrammer defined-classes which we create it.

The class contains data (in the form of variables andproperties) and behaviors (in the form of methods to process these data). Wewill understand this concept more later in the article.

When we declare a variable in a class we call it membervariables or instance variables. The name instance come from the fact that whenwe create an object we instance a class to create that object so instance of aclass means object of that class and instance variable means variable thatexists in that class.

The Object : It’s objectof some classification (or class, or type. All means the same thing) and whenyou create the object you can specify the properties of that object. What Imean here is me as an object can have a different properties (Hair Color, Age,Height, Weight) of you as another object. For example, I have a brown eyes andyou have a green eyes so when I create 2 objects I will specify a browncolor for my object’s Eyes Color property and I will specify a green color foryour object’s Eyes Color property.

So to complete my introduction to Classes we must discussProperties and Variables.

Properties and Variables:

Variables declared in a class store the data for eachinstance, What that means ? means that when you instantiate this class (thatis, When you create an object of this class) the object will allocate a memorylocations to store the data of its variables. Let’s take an example tounderstand it well.

class Person
{
public int Age;
public string HairColor;
}

This is our simple class which contains 2 variables. Don’tworry about public keyword now because we willtalk about it later . Now we will instantiate this class (that is, When youcreate an object of this class).

static void Main(string[]args)
{
Person Michael = newPerson();
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 someof 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 Persontype. After creating the 2 objects we initialize the instance variables forobject Michael and then for object Mary. Finally we print some values to theconsole. here when you create Michael object C# compiler allocate a memorylocation for the 2 instance variables to put the values there. Also the samething with Mary object the compiler will create 2 variables in the memory forMary object. So each object now contains a different data. Note that wedirectly accessed the variables and we put any values we want, Right ? so maybesomeone doesn’t like me will put in my object’s variable Age value of 120 yearsso I will not get any kind of jobs. But wait there are a solution for thisproblem. We will use properties.

Properties:

Properties is a way to access the variables of the class ina secure manner. Let’s see the same example using properties.

class Person
{
private int age;
private string hairColor;
public int Age
{
get
{
returnage;
}
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 please just care about the new2 properties that I created it here. So the property consists of 2 accessor.The get accessor which is responsibleof retrieving the variable value, And the set accessor which is responsible of modifying the variable’svalue. So The get accessor code is very simple wejust use the keyword return withthe variable name to return its value. so the following code:

get
{
return hairColor;
}

return the value stored in hairColor.

Note :the keyword value isa reserved keyword by C# (that is, reserved keywords means that these keywordsown only by C# and you can’t create it for other purpose. For example, Youcan’t create a variable called value .Ifyou did that C# compiler will generate an error and to make things easierVisual Studio.NET will color the reserved keywords to blue.)

Let’s put this code at work and after that discuss theset accessor.

static void Main(string[]args)
{
Person Michael = newPerson();
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 last example themodifications that I used only properties to access the variable instead ofaccess it directly. Look at the following line of code

Michael.Age = 20;

When you assign a value to the property like that C# willuse the set accessor. The great thing withthe set accessor is that we can controlthe assigned value and test it and maybe change to in some cases. When youassign a value to a property C# change the value in a variable and you canaccess 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 reasonI want any object of type Person to be in age between 18 and 65. Here I testthe value and if it in the range then simply I will store it in the variableage and it it’s not in the range I will put 18 as a value to age. It was just asimple example for the properties but there is a complete article about propertiessoon.

How we create objects and classes ?

We create classes by define it like that:

using the keyword class followedby the class name like that

class Person

then we open a left brace “{” and after we writeour methods and properties we close it by a right brace “}”. That’show 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 variablecalled age. In the second line we specified first the type of Object we need tocreate followed by the object’s name followed by a reserved operator called new and we end by typing the class name again followed byparenthesis “()”.

Let’s understand it step-by-step. Specifying the class nameat the beginning tell the C# Compiler to allocate a memory location for thattype (C# compiler knows all the variables and properties and methods of theclass so it will allocate the right amount of memory). Then we followed theclass name by out object variable name that we want it. The rest of the code”=new Person();” callthe object’s constructor. We will talk about constructor later but for nowunderstand that the constructor is a way to initialize your object’s variablewhile you are creating it not after you create it. For example, The Michaelobject we created it 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 listso I initialized the variables while I’m creating the object. But for this codeto work we will need to specify the constructor in the Person class and I willnot do that here because constructor section will come in later articles. Ithink you got a good introduction about Classes and Objects not I will completein in my next article and I will talk about constructors and building blockscoping. I hope you got a new thing from my article.



About the Author:

Michael Youssef is 20 years old and he’sworking with Microsoft technologies since he was 17. He is working with VB,VB.NET, C#,ASP, ASP. NET, XML Web services, COM+, SQL Server 2000, Windows 2000Server, Active Directory, Networks design. He is MCSD.NET, MCDBA, MCSE, MCSAand he’s working now as a .NET Trainer in Egypt. Michael can be reached atmichaellabibat@hotmail.com .

Related Articles :