C# and .NET Basics

Methods

Spencer Schneidenbach

Spencer Schneidenbach

Aviron Software, Microsoft MVP
C# and .NET Basics

Check out a free preview of the full C# and .NET Basics course

The "Methods" Lesson is part of the full, C# and .NET Basics course featured in this preview video. Here's what you'd learn in this lesson:

Spencer discusses methods in C# which are ways of encapsulating logic and performing reusable tasks. Spencer covers the structure of a method, including access modifiers, return types, method names, and parameters. He also demonstrates how to declare and use methods with different signatures, as well as how to declare void methods that do not return a value.

Preview
Close

Transcript from the "Methods" Lesson

[00:00:00]
>> Spencer Schneidenbach: So let's talk a little bit more about methods. Methods are basically ways of doing reusable things, right? There are ways of encapsulating logic such that you can say that this thing does x, it computes this value, it modifies this point in memory. So a method is really about doing.

[00:00:21]
And the first method that we looked at, of course, is our main method here, which is the entry point into the application. It's kind of the standard way that you get into.net is using the main method, but a class we can declare other methods besides main Of course.

[00:00:41]
There are many different there's many different places and ways that you can declare a method and they're all kind of, they all follow this very kind of same pattern or structure as you will. They're typically gonna have an access modifier. They may have a, another modifier depending on what kind of method it is.

[00:01:02]
We'll just, we'll get to that as we dive further in. It will have a return type and it will have the name of the method followed by any parameters that the method has. So one of the things we talked to that I mentioned that C-sharp has a particular way of styling things.

[00:01:20]
A C# style for methods is to declare them as pascal case. Which is means that a capital letter which is different from a lot of other languages which usually do camel case, where the first letter is lowercase. And C# will tell you, hey, this is the preferred style if you did type it as and declare it as a method as something named in a way that Microsoft doesn't tell you.

[00:01:43]
And I tend to actually exclusively stick to Microsoft styling roles, because that's what most other developers expect. I mentioned there are access modifiers, so you'd be able to say, for instance, that a public method on this program class would be exposed to other members. And other classes and other pieces of code, even outside this library.

[00:02:12]
For the purposes we're gonna keep most things public, just to kind of we'll just for clarity sake. But as we get into inheritance and we talk really about like class and object-oriented programming a little more, we will definitely talk about these because these are definitely important.
>> Spencer Schneidenbach: So, let's copy paste this very simple, very contrived method.

[00:02:33]
Of course, we have this built into the language, but as far as demonstrating all of the different parts of the language you're concerned, I think an example like this kind of does it well. You have your access modifier here. It is optional. If you don't, if you exclude it, it's private and only accessible by the program class.

[00:02:50]
You have the return type, which in this case is int because all we're doing is taking these and adding these two numbers together. We have the name of the method, which again is pascal case, and then we have the variable declarations. So some things to note about kind of how a method name and a method is unique is made unique.

[00:03:13]
If you try to copy paste this method, it's gonna throw a compiler error at you and say, this is already defined with the same parameter types. A method is defined by what's called its signature, and its signature is its name, followed by what parameters it takes in. So if we were to add, for instance, int c here, and modify even without modifying this method, the compiler stops complaining at us and says, okay, that's a valid method.

[00:03:36]
This is what's called method overloading. So you can have a method with multiple ways of calling it, multiple signatures, and they could do different things, have different behaviors, depending on what's passed into the method. So say for instance, we wanted to add a 1, int b =2. When we call add numbers, and actually we're gonna declare these as static.

[00:04:08]
This main method can't use AddNumbers unless they're all declared a static in this case, which we'll get into a little bit more a little later. And then we will say AddNumbers. And you can say that as we have the IDE will happily tell us that there's two different ways you can call this.

[00:04:24]
So you can call it here or you can call it here. So we'll show you the method signatures. And this is one of the things I love about.net is their investment in the tooling and it really makes APIs discoverable, makes it very easy to use. It's also helpful that Microsoft really, really is stringent and about documenting the behaviors of these methods, which is really cool at all, which is really cool.

[00:04:45]
So like declaring a variable, we can set the value of this return type because this is an int. We can set this to a int, call it C equals. And then we can say that Console.WriteLine, we can say write C. And we're good to go dent that and if we run it, you'll see that it will not run.

[00:05:09]
You will see that it indeed done that run. You'll see that it does print the three as we expect. So let's see, what else have we got for methods? A couple of different ways of declaring parameters, which are useful to know for now. You can assign default values to parameters, so for instance, if you wanted to have a parameter automatically be assigned to 5 why you would do that in this particular case.

[00:05:47]
I'm probably not gonna write code like this but if you wanted to default value on this parameter, you can absolutely do that. It's typically gonna be a value parameter. A value parameter is gonna be allow you to do this, strings will allow you to do this. But if you have something that's like a instance of a class, a reference type, it's typically not gonna allow you to just assign it to a random instance.

[00:06:11]
It's not gonna allow that, but you can assign default values, and I do wanna kind of point out what that looks like. If you call it, you can actually call add numbers then with just one argument. And if you hover over, you can see that it knows that it's calling int a b5, but it'll show you, hey, we didn't have to pass in the second argument.

[00:06:30]
If you try to move this over here, compiler will give you an error saying default values, the optional parameters must appear after the required parameters. So a little bit of a restriction there. As well as you can choose if you want to take in a series of parameters.

[00:06:54]
So in this case, you can tell it, you can take in any number of integers. So we could say add numbers one, and you can see, when we hover over it, it's calling the correct one. But we can add 2,3, 4, we can have all. We can pretty much with this params and followed by an array.

[00:07:13]
This is how you declare an array, which we'll talk about in a little bit. This allows you to have a variable number of parameters. Params, you can have other parameters in front, for instance, but the params declared must come at the end. Yes, Mark?
>> Mark: Does every method have to be inside of a class or can you have a generic method that is kind of global?

[00:07:39]
>> Spencer Schneidenbach: Not quite most the time you're gonna declare methods inside of classes, but you can declare what's called a local function. This is a relatively new feature, and I do use it quite a bit, which is that you can declare a function now inside of a block of code.

[00:07:53]
So you could have your add numbers here, and then have int a, int b- and then return zero. You can declare them in line inside of the block of code. So that's the thing that you can do. Most of the time, I'm declaring them in the context of a class.

[00:08:12]
Really good question.
>> Student 1: I feel like I'm not quite understanding the purpose of params so that's for like an optional.
>> Spencer Schneidenbach: Purpose of params is really to give youu a 0 to n or any really any upper bound number of parameters that you can call add numbers and then not call it with any entity with any arguments at all.

[00:08:41]
It's just basically asking for a list of integers. You can give it 1, and here it's still just gonna give you. It's gonna be an array this, when it's called, this is gonna be an array of one integer. And then when you do 2 and 3, it will be an array, which is a set of data, right?

[00:08:59]
Of three integers in that case. So params just allows you to kind of have an infinite number of parameters as it were. So good question.
>> Student 1: But it needs to come at the end because then they're optional.
>> Spencer Schneidenbach: Yeah, well, it needs to come at the end very similar to optional parameters because you could call any number of params here, but if you try to declare it with like a string name at the end.

[00:09:27]
It's gonna complain and say a params parameter must be the last parameter. So it's a compiler rule, right? It's to kind of protect you from shooting yourself in the foot as they say. Good question. So we've talked about value returning methods, which are things that return a value, but sometimes methods just do things, right?

[00:09:45]
Sometimes they just process or maybe they'll print some data. So there are what I like to call, and I don't know that there's common parlance around this, but a avoid returning method. I'll talk about why I call it that here shortly but essentially, a method with a void type as its return type, which basically essentially says, I don't return anything.

[00:10:09]
I just do something, right? So this isn't something that you can get a value out of, right? So if you go up here and you say and you declare var message, equals print message. It's gonna complain at you and say that you can't assign void to an implicitly typed variable.

[00:10:26]
You can't assign void at all. So this essentially just is a method that does not have a return value, right? It just does stuff which are extremely useful for lots of reasons. Most of the time, I'm declaring some kind of value, returning function and then my void returning function is gonna be doing some kind of processing of all of those different other functions.

[00:10:52]
>> Spencer Schneidenbach: They otherwise share the same properties as functions that return a value. They have modifiers, the only differences is instead of a return type, you put void. Return keyword is not required here. You need to be able to exit out of this so you can see that it's still, it's complaining about this, but now it's gonna be complaining that there's no return value in all code paths.

[00:11:16]
So that is that. So in methods that return values, the return statement is required. You can return a statement. You could actually also throw an exception, but we'll get to that when we talk about exception handling and throwing exceptions. Last thing I will mention about values or functions that return or methods that return values.

[00:11:39]
So we can declare multiple return statements with branching logic depending, and we'll talk about the different kinds of branching logic as we get further in. But if you declare a method called, say, static so that anything can use it. bool IsEven, an int number you can have branching logic.

[00:12:01]
So I'm gonna show you a little bit of arithmetic operators. So this one's called modulus and if you're a developer, this will look very familiar, but it's basically the remainder after you divide. So if number modulus 2=0. So if the remainder is 0, it's an even number. So you would return true, and you notice that the method is complaining that not all code paths return a value.

[00:12:30]
So because of that, because the it could exit this method and still not have a return value, we do need to return false here, which is a good thing that's. It's one of the things that I love about somebody asked if C sharp is strictly typed. I love the fact that it has you follow a very strict set of rules.

[00:12:48]
And this is one of those set of rules that just prevent, as I like to say, foot guns. It's not like that in the most basic form of JavaScript, but it is certainly like that in C Sharp. Any questions about methods before we move on?
>> Student 1: Just real quick, is the standard within C-Sharp to use double equal signs instead of triple equals?

[00:13:13]
>> Spencer Schneidenbach: Good question. There is no triple equals inside of C-Sharp. So double equals is one of those, let's say what I say in the JavaScript ecosystem is kind of one of those dirty word. [LAUGH] One of those things that you tend not to use, but there's no triple equals.

[00:13:31]
There's no type coercion, as it were that it doesn't have the same semantics as it doesn't JavaScript, great question. So if you tried triple equals here, so it doesn't do any sneaky type conversion under the hood, there are some languages, VB.NET, comes to mind that you can turn off all of its safety.

[00:13:52]
You can turn off all of its language safety and have it coerce types when you're doing comparisons. That's not a thing in C sharp, though.
>> Mark: The static mean that you can use the method without initializing the class.
>> Spencer Schneidenbach: That is correct. That's what static is for. So static is really just a is basically a helper method that doesn't rely on any other things, any other variables inside of your class if you've got.

[00:14:16]
And we'll talk about this when we talk about classes. We'll talk about instances of types and objects. When we get into that, it will kind of come together more but essentially static just means that you can access it without having an instance of the type. So you if you declared this math class as something that you can just instantiate, so you could do var math = new Math.

[00:14:41]
And this is getting way ahead, so we will cover this in more detail. But you don't have to have an instance of this class available in order to call the AddNumbers function. That's what it's intended to be, kind of utility functions.
>> Spencer Schneidenbach: Yes.
>> Student 1: You mentioned earlier that void only doesn't necessarily need a return.

[00:15:04]
So I was just trying to think through a case where those type of functions would be used. Would that also be used in creating like utility and helper functions as well?
>> Spencer Schneidenbach: Yeah, it could. So if you wanted to, for instance if you wanted to print a certain message to a console in a certain shape or log something there, you had a utility function.

[00:15:27]
Let's say that you had a message that you wanted to write to a database, print a console, and also log to some kind of logging system. You might have a void returning method or a void method or just a straight method that does all three of those things, but doesn't necessarily return a value because you don't need to in that case.

[00:15:43]
Does that make sense? Good question.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now