What is a “method” in C# programming?

778 views

I am currently going through “Become a C# Developer” on LinkedIn Learning and watching this course “Understanding C# syntax”, the instructor – Bruce Van Horn – went on to explain properties but he never explained what is a method? I mean, what is a method? What is it used for? How do I know where to look for method?

Is this simply just a word – like in real world – a method to do something? E.g. completing a task using method 1 or method 2?

TL;DR: what is a method? What is it used for? How do I know where to look for method?

Also, I have Googled this using keyword, but no real good explanations come out of it that I understand.

In: Engineering

6 Answers

Anonymous 0 Comments

Methods are technically different from functions, but in practice the two terms are identical.

Another answer has explained what a method is, so I want to explain in a bit more detail what properties are in C# because it’s not fully intuitive.

A ‘field’ is a variable attached to an object. So, if you have a Person class and you say that class has an Age, represented by an int variable, that’s a field.

In programming we often want to control how we access fields. This is why we use ‘public’ and ‘private’ — they let us decide who gets to see the inner workings of a class. You could declare the Person class’ Age field as private (nobody outside Person can see it) or public (everyone can see it).

A property is a more detailed and powerful way to determine the visibility of fields. In practical terms, they’re methods — nothing less and nothing more. You have a private field, and then public methods which control how other parts of your program see or set the value of the private field. An example:

class Person

{

private int age;

public GetAge() { return age; }

public SetAge() { age = value; }

}

You could, of course, also use that SetAge() function to do ‘validation’ — making sure nobody sets the variable to something stupid or nonsensical, like a negative number or 20,000.

You are viewing 1 out of 6 answers, click here to view all answers.