0
What are and how to i use classes and methods in C#
Guys i need some help here. I am learning C# and it's been going well so far. I even learned the loops. But classes and methods are just so confusing to me. I know how to create the but o still don't understand their purpose and i don't know how to use them properly. I would really apreciate some help. (p.s. i have watched a bunch of tutorials)
6 ответов
+ 2
Well @Andrew, to show you how to use classes and call its methods, let me give you an example:
Let's try and solve a challenge that was posted before here in Sololearn (with some modifications), but by using classes.
The challenge was: Ann is counting to 10. Bob, his friend is a mathematician and likes numbers, so everytime Ann would say
a number he would add it to a running total but if the number is a perfect square he would be so excited that he would add it
twice.
What is the total that Bob gets to?
To solve this challenge, I created two Classes.
Person:
it has a 'name', and because the persons will count I added a 'number' to it so it can save the current number they are.
It also has a count method.
Mathematician:
it is a Person also and has al the caracteristics of Person. But also knows when a numbers is a perfect square and how to sum.
Now in Main, I created Ann (Person) and Bob(Mathematician) and made them count:
https://code.sololearn.com/can1HMtoKeSI/?ref=app
This is an example of using Classes.
Hope it helps.
+ 3
The need for Classes appeared we the need for programers to model their program (representation of a problem) according to the world
(the world is composed of objects). For large programs it makes maintaining the code easier.
Classes are like an abstract representation of a Type (or class) of object.
A programer can create a class Animal, for example, and give caracteristics to it like 'name', 'color', ... (atributes), and behaviors like eat, sleep, ...(methods).
After that he can create objects of that class:
Animal dog = new Animal();
and can use codes like this:
dog.sleep() or dog.eat()
This make the programmer write codes that looks like english.
Before classes the problems were represented in a functional way (with functions) and it represented the problem in the point of view of the computer internals.
+ 1
It doess help. Thank you so much for taking the time to write all that stuff for me. 👍🏻
0
Thank you for that. But how doaes the "Animal dog = new Animal() " work? why do i need to create a new class every time i add an animal?
0
A class is a blue print. And a dog is an object.
So you create the animal class once.
And use the functionality of the animal class as many times as you want every time you create a object.
0
Yes. That's all good but how do i USE them. How do i effectively call methods? When is it a good time to call them?