In my last
Post I described in some way what a class is and how it is defined approximately, I will continue with defining a class definition and methods in and outside a class,
class Person
{
string FirstName {get; set;}
string LastName {get; set;}
}
Methods
So consider a method something like an action that is done into application logic, for example a method could be Sleep() for the current Person class, that's an logical action that applies inside an entity in our case the Person class, a method is contained with some part like this bluePrint:
void MethodName(aType myparameter)
{
// body
}
The method as we can see is contained with a 'Method name' section, 'Parameter' section and the 'body' section, the method name section we use for call or raise the method, the parameter(s) we can use for doing several actions in several conditions (it really depends what we want to achieve) and at last the body section is the main part, there we define our logic. This method can be placed into our Person class and if we do that, the Person class is able to call that method from an instance, an instance is simple a class declaration with the new keyword. For the parameters we are able to add as many parameters as we need, but it isn't a good practice to pass much parameters into a method, a simple rule when we can write our own method is: "If we need some kind of procedure or code logic to repeat the same action(s) over and over again, we define our method and just call it." I will rewrite the person class with a method:
class Person
{
string FirstName {get; set;}
string LastName {get; set;}
void Sleep(int hours)
{
// body
}
}
The class above has now a method called 'Sleep', with a parameter 'hours' of type 'int', logically if we call this method and pass for example value 3 as the parameter value, the person will sleep for 3 hours (nice Idea for now :D). Declaration of a class is really simple, a
declaration means simple 'making use of an type' and call/use his 'functions (properties,methods,events,delegates...etc)', I will declare the Person class and make a call of the Sleep Method:
// the declaration of the class
Person p =
new Person();
p.Sleep(3); // the method calling code
That was simple, right? what here is done is simple, we have made a use of the person class and call his sleep method.
What's next?
In the next post I will try to expand the example of making use of a class with name and last name, feel free to comment or to share the content.