Jump to content

C# Basics of Methods/Functions (Need Info)

kaddle

hello i am learning C#. i am learning about methods/functions (i know they are the same thing). i am learning from a website and a video so if i link pics below for reference those are likely the sources. i'm trying to learn the basics of functions. i pretty much mostly get the basics of it but there are some things i'm confused about. if i'm going to write down the basics in my notebook i need a clear understanding of it. any detailed explanations about the basics of methods/functions will help a lot, or you can just answer the questions i have and clear up my confusion. any help is appreciated. i'm still very new to C# and programming in general so a lot of my confusion could be due to inexperience.

 

what i know so far:

a method/function is essentially a block of code for the purpose of performing a specific task. when the program runs then the code in the highest priority method will run, and the only method that will run automatically when the program launches is the highest priority method. whenever the method is called it will perform the task that the method is programmed to perform. i'm assuming that methods are the main way or the only way in C# to actually make the program do stuff. i also know that the general layout of a method is:

<visibility> <return type> <name>(<parameters>)
{
        <function code>
}

 

questions/things i'm confused about:

well i guess my first bit of confusion is about how code is ran in C# in general. when the program is ran does it start with processing the first line of code and continue from there? are all languages like that? if so then the first method in the C# program will always be ran first, or is there something else that determines which method is the highest priority?

 

the guy in the video says he will talk about the "static" value later on but it keeps bugging me. as shown in the picture below it is used twice. is static really a visibility value or is it something else? what does it mean?

 

are the parameters in methods kind of like mini disposable variables? i ask because it seems that the layout of the parameters is similar to variables and each time the method is called the values of the parameters can be changed, as shown in the picture below.

 

are you only able to call a method from another method? in the video i am learning from where the image below is from the guy only mentions calling a method from another method. this notion was super confusing at first but after thinking about it some more it seems a bit less confusing. i guess we can think of the first method as being a layout for how the program will run in terms of managing other methods, kind of like a conductor in a musical. then the other methods are designed to perform specific individual tasks like the musicians in the musical. is this accurate? if so, is this the pattern that all programs written in C# will follow? it still seems a bit confusing so a detailed explanation is much appreciated.

 

7ituy7rte.png

Link to comment
Share on other sites

Link to post
Share on other sites

19 minutes ago, kaddle said:

i pretty much mostly get the basics of it but there are some things i'm confused about. if i'm going to write down the basics in my notebook i need a clear understanding of it

Most of your questions are quite hard to give complete explanations of without first explaining some things about object orientation. So these answers may accidentally lead to more questions than they give you answers. Never-the-less:
 

20 minutes ago, kaddle said:

well i guess my first bit of confusion is about how code is ran in C# in general. when the program is ran does it start with processing the first line of code and continue from there? are all languages like that? if so then the first method in the C# program will always be ran first, or is there something else that determines which method is the highest priority? 

By design, the first line to be "executed" in the sense of running your program is the first executable line in the Main function. What I mean is:

class program
{
  static void main(string[] args)
  {
    // This line is not executable. Therefore it will not execute.
    int i = 3 + 4; // This is the first executable line. Therefore, execution will start here
  }
}


Languages don't necessarily need to be like that, but many are.
 

 

24 minutes ago, kaddle said:

the guy in the video says he will talk about the "static" value later on but it keeps bugging me. as shown in the picture below it is used twice. is static really a visibility value or is it something else? what does it mean? 

Are you watching Bob Tabor by any chance? I watched his videos too, they are fairly good. But this is going to be a hard one to explain without first explaining what a "class" is, which is why your teacher said he would wait. That's what he's waiting for.

But, just to satisfy your curiosity for a while, "static" means that a method (or really any other member) is the same for every instance of a class. "static" is not a visibility modifier.

 

29 minutes ago, kaddle said:

are you only able to call a method from another method? in the video i am learning from where the image below is from the guy only mentions calling a method from another method. this notion was super confusing at first but after thinking about it some more it seems a bit less confusing. i guess we can think of the first method as being a layout for how the program will run in terms of managing other methods, kind of like a conductor in a musical. then the other methods are designed to perform specific individual tasks like the musicians in the musical. is this accurate? if so, is this the pattern that all programs written in C# will follow? it still seems a bit confusing so a detailed explanation is much appreciated. 

It is more correct to say that a method can be called from any member that can invoke an operation. In practice this means that all of the code that gets run will be in methods, or things that automatically get converted to methods/functions.

At the level that you are at, yes: your main method is a layout for how the program should function, pretty much just like a conductor in a musical, except for that conductor is also playing an instrument.

If you want some advice, stop thinking ahead. C# is a very mature and well developed language with lot's of features and rules, some of which can be fairly complicated. You would do best to write your questions down, and answer them when you get a little further than "hello world, but in a function".

 

ENCRYPTION IS NOT A CRIME

Link to comment
Share on other sites

Link to post
Share on other sites

4 hours ago, kaddle said:

hello i am learning C#. i am learning about methods/functions (i know they are the same thing).

Some are anal about C# only having methods because they don’t call them functions so it’s good to know both terms but to refer to them how the language refers to them. C# has methods. 

 

Quote

what i know so far:

a method/function is essentially a block of code for the purpose of performing a specific task.

That’s the “meta” use of it & good practice. It’s basically a short way of writing a lot of code. It saves a lot of copy/paste. I could for instance tell someone to change oil on a car like this:

1. Position oil pan under car

2. Open drain plug

3. When oil tank is empty, close oil drain.

4. Fill oil into oil tank.

or I can just say change oil. 

That way I have condensed 4 steps into 1 phrase. 

Quote

when the program runs then the code in the highest priority method will run, and the only method that will run automatically when the program launches is the highest priority method.

Yes & no. 

If i understand your question properly, 

There’s something called arguments. This is a little advanced but.... you can name any number of methods the same thing ONLY if they accept different arguments. 

I could take the change the oil example & expand upon it. 

I could say 

1. Change the oil

2. Change the oil with oil type: (oil type) 

3. Change the oil with filter (filter type) 

now the mechanic can either change the oil, he can change the oil and put in a specific type of oil or he can change the oil & replace the filter. 

(Let’s ignore what’s recommendes for cars please. It’s only an example.) 

(if that didn’t make any sense, ignore it. This is a little advanced.) 

Quote

whenever the method is called it will perform the task that the method is programmed to perform.

Yes. It’s exactly like copying and pasting the code from within the method to where you called it. 

Example:


main() {

int x;

console.readline(x);

CheckValue(x);

writeline (“thanks for playing!”);

}

 

Void CheckValue(int x){

if (x>5)

console.writeline(“x is a big number.”);

else console.writeline(“x is a small number.”);

}

is exactly the same as writing

 


main() {

int x;

console.readline(x);

if (x>5)

console.writeline(“x is a big number.”);

else console.writeline(“x is a small number.”);

}

writeline (“thanks for playing!”);

}

 

though you cannot always copy/paste as easily as I have. 

Quote

i'm assuming that methods are the main way or the only way in C# to actually make the program do stuff.

Yes & no. Yes because technically C# starts with a method & all code is written within the main or other methods. 

 

No because you can write C# without ever calling any functions & it won’t be a program, it’ll be just variables.

 

Also no because you CAN write all your logic in the main. 

Quote

i also know that the general layout of a method is:


<visibility> <return type> <name>(<parameters>)
{
        <function code>
}

That’s it. If you don’t put a visibility type, it defaults to private. Some are anal about putting private anyway. I personally don’t because I like to eventually stop typing. 

There’s also some other things you can put before visibility. Though I think it’s better characterized as accessibility. 

Your house is publically visible but privately accessible. Only you or your family can use it. Except for variables. ... stick to the visibility thought. 

Quote

questions/things i'm confused about:

well i guess my first bit of confusion is about how code is ran in C# in general. when the program is ran does it start with processing the first line of code and continue from there?

Yes/No. 90~99% of languages have an entry point or main method. 

When the program starts, it looks for that method. THEN it executes the main method one step at a time from top to bottom. 

Quote

are all languages like that?

Yes but technically you can compile code into non-programs. This way you can have compiled code that will run quickly and call it from other languages.

 

IE it May be easier to write logic to do this type of processing but 90% of your program is easier to write in the other language. Write the 90% of the language as a program in language A. Then write the 10% of the program in language B. 

Quote

if so then the first method in the C# program will always be ran first, or is there something else that determines which method is the highest priority?

Whatever is the main in the program class will run first. There may be ways to change it if you really wanted but there’s no point. 

It’s like “I can drive my car backwards on the highway but I can also just drive forwards.” 

Quote

the guy in the video says he will talk about the "static" value later on but it keeps bugging me. as shown in the picture below it is used twice. is static really a visibility value or is it something else? what does it mean?

Static means you don’t need to “initialise” the class to use it. 

You know how you make an integer and give it a value & then use it? 

Normally you’d make a class & then treat it like a variable (console is a class & you call the method writeline() from it.) however static classes (like console) don’t need to be created. 

Quote

are the parameters in methods kind of like mini disposable variables?

Exactly that. 

Quote

i ask because it seems that the layout of the parameters is similar to variables and each time the method is called the values of the parameters can be changed, as shown in the picture below.

I don’t see a picture. 

Quote

are you only able to call a method from another method?

Technically because the main is a method yes you have to. 

 

My first answer said “functions doing 1 thing is good practice but not necessary.” 

If you write a complex function, you may call other functions to keep it neater. OIL CHANGE EXAMPLE:

In the function change oil we unscrew the drain plug. 

I could also say “find the right size wrench, turn to the left, repeat.”

however i kinda phrased it like a method. 

 

Unscrew (drainPlug);

waitForOilToDrain();

AddOil();

 

Private unscrew (drainPlug) {

wrench = drainPlug.boltType;

while (screwed)

wrench.unscrew(drainPlug);

}

 

Quote

i guess we can think of the first method as being a layout for how the program will run in terms of managing other methods, kind of like a conductor in a musical. then the other methods are designed to perform specific individual tasks like the musicians in the musical. is this accurate?

Kinda. 

Quote

if so, is this the pattern that all programs written in C# will follow?

How most programs work period. 

Quote

it still seems a bit confusing so a detailed explanation is much appreciated.

It is. Once you get it though, you get it. Walking is difficult & takes us 2~ years to do. 

Quote

 

7ituy7rte.png

The main method in the program class is the “entry point” and step 1 in the program. SayHi is a short way of typing that long console write line method. It’s faster to pass the arguments & they look uniform. It’s very difficult to get it to mess up. 

 

Edit:

i always recommend this book:

learn C# in a day and learn it well. 

 

Its like 10 bucks & has all the important information to C# in like 100 pages. (115?) 

Link to comment
Share on other sites

Link to post
Share on other sites

I think that everyone before me answered all questions twice, so I dont really have to add something else than: 

programming is hard to learn but as soon as you get it, it can be great fun to do and sonetimes takes you headaches to solve a problem, but as soon as you get it solved its a great satisfying feeling. :D 

Link to comment
Share on other sites

Link to post
Share on other sites

I suppose I could chime in as well.

6 hours ago, kaddle said:

well i guess my first bit of confusion is about how code is ran in C# in general. when the program is ran does it start with processing the first line of code and continue from there? are all languages like that? if so then the first method in the C# program will always be ran first, or is there something else that determines which method is the highest priority?

Yes and no. By default, most languages are expecting a "main" function to start from. But it doesn't actually have to be this.

 

While I don't know the exact specifics of how programs are launched in an OS, but when you have a program that's running on "bare metal", i.e. directly on the CPU without an OS (which could be the OS), the CPU is hardwired to run code in what's called reset vector. This is an address that the CPU looks for to start running code and this address can point to anything. If you're running a C program in this fashion, like on an Arduino or a Cortex M, there's startup code that gets run to initialize things, and then it jumps to the C program. Most startup code will look for "main", but you can have it point to some other function.

 

6 hours ago, kaddle said:

the guy in the video says he will talk about the "static" value later on but it keeps bugging me. as shown in the picture below it is used twice. is static really a visibility value or is it something else? what does it mean?

Static in C# means that the type itself is how you reference the type, rather than an instance of the type. For classes, if you declare a class as static, it means you cannot create a new instance of it. The class itself is the instance. If you declare a static member in a class, but not the class itself, you can actually use the member without creating a new instance of the class.

 

So for example, if we had this class:

public static class TemperatureConverter
{
    public static double CelsiusToFahrenheit(string temperatureCelsius)
    {
        // Convert argument to double for calculations.
        double celsius = Double.Parse(temperatureCelsius);

        // Convert Celsius to Fahrenheit.
        double fahrenheit = (celsius * 9 / 5) + 32;

        return fahrenheit;
    }

    public static double FahrenheitToCelsius(string temperatureFahrenheit)
    {
        // Convert argument to double for calculations.
        double fahrenheit = Double.Parse(temperatureFahrenheit);

        // Convert Fahrenheit to Celsius.
        double celsius = (fahrenheit - 32) * 5 / 9;

        return celsius;
    }
}

You do not use it like:

TemperatureConverter converter = new TemperatureConverter();
string celcius = converter.CelciusToFahrenheit(fahrenheit);

 

You just use the class itself directly:

string celcius = TemperatureConverter.CelciusToFahrenheit(fahrenheit);

 

If it's a class with static members:

public class Automobile
{
    public static int NumberOfWheels = 4;
    public static int SizeOfGasTank
    {
        get
        {
            return 15;
        }
    }
    public static void Drive() { }
    public static event EventType RunOutOfGas;

    // Other non-static fields and properties...
  	
  	public int gasRemaining;
  	public Autombile(int startingGas) {
    	gasRemaining = startingGas;	
  	}
}

Then in this case, you have to create an instance of the class to use it, but where it gets potentially confusing is to access the static members, you have to use the class name itself:

Autombile car = new car(15);
Automobile.Drive();
int wheels = 0;
int gasTankCap = 0;

gasTankCap = Automobile.SizeOfGasTank();
wheels = Automobile.NumberOfWheels;

car.Drive(); 			// Will not work
car.SizeOfGasTank(); 	// Will also not work
car.gasRemaining;		// Will work
Automobile.gasRemaining; // Will not work either.

This is useful if you want a class or its children to have the same method/member and definitions. Though do note if you declare something static, you also have to define it. In this case, you can't leave NumberOfWheels uninitialized.

6 hours ago, kaddle said:

are the parameters in methods kind of like mini disposable variables? i ask because it seems that the layout of the parameters is similar to variables and each time the method is called the values of the parameters can be changed, as shown in the picture below.

Yes and no. If the parameter is passed by value, it's discarded the moment the function returns, or more precisely, the moment you leave the current scope (you can define new variables in say an if-block that will only live for duration of that if-block) If the parameter is passed by reference, anything done to that parameter affects the original copy as well.

 

https://docs.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/types-and-variables has what data types are passed by value and what's passed by reference. You can in C# pass a value type by reference if you need to.

 

6 hours ago, kaddle said:

are you only able to call a method from another method?

You can call as many methods as you want from another method, and call methods within those methods.

6 hours ago, kaddle said:

in the video i am learning from where the image below is from the guy only mentions calling a method from another method. this notion was super confusing at first but after thinking about it some more it seems a bit less confusing. i guess we can think of the first method as being a layout for how the program will run in terms of managing other methods, kind of like a conductor in a musical. then the other methods are designed to perform specific individual tasks like the musicians in the musical. is this accurate? if so, is this the pattern that all programs written in C# will follow? it still seems a bit confusing so a detailed explanation is much appreciated.

It is a typical way of doing things.

Link to comment
Share on other sites

Link to post
Share on other sites

thanks everyone for the advice and information.

On 1/31/2019 at 3:13 AM, straight_stewie said:

Are you watching Bob Tabor by any chance? I watched his videos too, they are fairly good. But this is going to be a hard one to explain without first explaining what a "class" is, which is why your teacher said he would wait. That's what he's waiting for.

the video i'm watching is

the website i'm learning from is https://csharp.net-tutorials.com/getting-started/introduction/

 

the lessons from each source are laid out similarly so it helps to have both of those perspectives.

On 1/31/2019 at 7:31 AM, fpo said:

i always recommend this book:

learn C# in a day and learn it well. 

 

Its like 10 bucks & has all the important information to C# in like 100 pages. (115?) 

are you talking about this book: https://www.amazon.com/Beginners-Hands-Project-Coding-Project-ebook/dp/B016Z18MLG?tag=linus21-20 ?

 

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×