Methods in C Sharp. Class methods Methods in c#

in lesson 16, meth talked about classes, well, I’ll continue this topic.
He declared variables public; in general, it is not recommended to declare them public if only methods work with them. These variables are called from any part of the code using class objects. Well, in general, there is not only this modifier (public), there are 3 more: internal - variables are available within 1 namespace, private - variables are available only within the class, and protected - almost the same as private, but only variables are also available to descendant classes. And about methods, they can also have the same modifiers (public, private, etc.) and can return a value (int, double, bool, etc.) and if a method returns a value, it must have parameters (which is what a method in parentheses), they are declared as variables and separated by commas, and when calling a method on them, the values ​​for them are specified in the order in which they are declared. And let's make a console calculator. Here's the code:

Using System; //connect the namespace class Program ( /* * assign 2 private variables * of type double, the modifier can * not be specified since it is * private by default */ double FN = 0.0; double SN = 0.0; public void SetFNandSN () //make a public method that does not return a value ( Console.WriteLine(); Console.Write("Enter the 1st number: "); FN = Convert.ToDouble(Console.ReadLine()); Console.Write("Enter the 2nd number : "); SN = Convert.ToDouble(Console.ReadLine()); /* * call the SimpleCalculate method * and there is no need to create an object since * the method is in the same class */ SimpleCalculate(); ) void SimpleCalculate() / /create a private method because it is called only from this class ( Console.WriteLine(); Console.WriteLine("Sum: " + (FN + SN)); Console.WriteLine("Difference: " + (FN - SN) ); Console.WriteLine("Private: " + (FN / SN)); Console.WriteLine("Product: " + (FN * SN)); class DemoProgram ( static int Main()); ( Program ob = new Program(); //create a new object int intvar1 = 0;< intvar1; i++) { ob.SetFNandSN(); //вызываем метод } Console.ReadKey(); //ожидаем нажатия любой клавиши return 0; //возвращаем значение 0 т.к Main() должен возвращать значение int } }

Console.WriteLine("How many times should I perform the calculation?");

Using and creating methods in a C# program is in many ways similar to the approach you already know from C++. Let's look at this in more detail. In C#, any method is a method of some class. For example:

Using System; class Man( public string name; public int age; public Man(string n,int a)( name = n; age = a; ) public void Show())( Console.WriteLine("Name = "+name+"\tAge = "+age); ) ) class Sample ( static void Main() ( try( Man obj = new Man("Fire",56); obj.Show(); ) catch(Exception er)( Console.WriteLine(er. Message); ) Console.Read();

In this example, we have a Man class with a Show method and a constructor. Please note that next to Show there is a public access specifier. If you do not specify it, it will be set to private by default and you will not be able to call it from the Sample class. To return values ​​and exit a method, just like in C++, the return operator is used. The principle of use is demonstrated in the example:

Using System; class SomeClass( public float x; public float y; public SomeClass(float a,float b)( x = a; y = b; ) public float Summa())( return x+y; ) public void Test(float t)( if(t == 0)( Console.WriteLine("0 was passed for division"); return; ) Console.WriteLine(" Result = ",(x+y)/t) ) class Sample ( static void Main) () ( try( SomeClass obj = new SomeClass(2,3); Console.WriteLine("Sum is = "+obj.Summa()); obj.Test(0); ) catch(Exception er)( Console.WriteLine (er.Message); ) Console.Read();

Passing parameters

In C#, there are two ways to pass parameters to a method, by value and by reference. In the first case, it is not the original variable that gets inside the method. and its copy, which is destroyed when the method exits without affecting the original variable. When passing values ​​of regular types such as int, double, etc. to the method. Pass by value is used. Therefore, when changing a parameter, there is no effect on the original variable. For example:

Using System; class SomeClass( public float x; public SomeClass(float a)( x = a; ) public void TryToSetTo99(float res)( res = 99; ) public float Mult(float res)( return res*x; ) ) class Sample ( static void Main() ( try( SomeClass obj = new SomeClass(2); float test = 5; obj.TryToSetTo99(test); Console.WriteLine(test); // 5 Console.WriteLine(obj.Mult(test)) ; // 10 ) catch(Exception er)( Console.WriteLine(er.Message); ) Console.Read() ) )

It is easy to notice that the test variable did not change its value after passing it to TryToSetTo99. Now let's look at the second method of passing parameters - by reference. In this case, not a copy of the passed parameter is passed, but a link to the original object, which allows you to modify the original. Class objects are always automatically passed by reference. For example:

Using System; class SomeClass( public int x; public int y; ) class SomeClass2( public void Set(SomeClass obj)( obj.x=1; obj.y=2; ) ) class Sample ( static void Main() ( try( SomeClass obj = new SomeClass(); SomeClass2 obj2 = new SomeClass2(); obj.y = 9; obj2.Set(obj); // passed by reference Console.WriteLine(obj.x+" "+obj. y); // 1 2 ) catch(Exception er)( Console.WriteLine(er.Message); ) Console.Read() ) )

How to change the value for a variable of type int or double when passing it inside a method will be shown in the next section. In C#, as in C++. you can overload methods. The rules for overloading are the same as in C++.

Static methods

A static method is a method with the static modifier. The difference between a regular class method and this one is that a method with a static modifier can be called without creating any class object. For example:

Using System; class Figure( public static void Draw())( Console.WriteLine("FigureDraw"); ) ) class Sample ( static void Main() ( try(Figure.Draw(); ) catch(Exception er)( Console.WriteLine(er .Message); ) Console.Read();

Differences between static methods and regular methods:

  1. Methods with the static modifier do not have a this reference.
  2. A method with the static modifier can directly (without specifying the object name) only call another static method.
  3. A method with the static modifier only has direct access to static data.
For example: using System; class Figure( public int a; public void Line())( Console.WriteLine("*************"); ) public static void Draw())( a = 78; // ERROR! !! a not static - member Console.WriteLine("FigureDraw"); //// ERROR!!! Line is not static - method ) public static void Draw2(Figure t)( t.Line(); / / And so it is possible!!! ) ) class Sample ( static void Main() ( try( Figure.Draw(); Figure.Draw2(); ) catch(Exception er)( Console.WriteLine(er.Message); ) Console .Read();

Methods

It should be noted that the official C# terminology makes a distinction between functions and methods. According to this terminology, the concept of a "member function" includes not only methods, but also other non-data members of a class or structure. This includes indexers, operations, constructors, destructors, and - perhaps somewhat surprisingly - properties. They contrast with the data members: fields, constants, and events.

Declaring Methods

In C#, a method definition consists of any modifiers (such as an accessibility specification), a return type, followed by the method name, then a list of arguments in parentheses, and then the method body in curly braces:

[modifiers] return_typeMethodName([parameters]) ( // Method body)

Each parameter consists of the name of the parameter type and the name by which it can be accessed in the body of the method. In addition, if a method returns a value, then a return statement must be used along with the return value to indicate the exit point.

If the method does not return anything, then the return type is specified void, since it is impossible to omit the return type altogether. If it does not accept arguments, then empty parentheses must still be present after the method name. In this case, it is not necessary to include a return operator in the body of the method - the method returns control automatically upon reaching the closing curly brace.

Return from method and return value

In general, a method can return under two conditions. First, when a curly brace is encountered that closes the body of a method. And secondly, when the statement is executed return. There are two forms of the return statement: one for methods of type void ( return from method), i.e. those methods that do not return values, and the other for methods that return specific values ​​( return value).

Let's look at an example:

Using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 ( class MyMathOperation ( public double r; public string s; // Returns the area of ​​a circle public double sqrCircle() ( return Math.PI * r * r; ) // Returns the circumference of a circle public double longCircle() ( return 2 * Math .PI * r; ) public void writeResult() ( Console.WriteLine("Calculate area or length? s/l:"); s = Console.ReadLine(); s = s.ToLower(); if (s == "s") ( Console.WriteLine("The area of ​​the circle is (0:#.###)", sqrCircle()); return; ) else if (s == "l") ( Console.WriteLine("Circle length equals (0:#.##)",longCircle()); return; ) else ( Console.WriteLine("You entered the wrong character"); ) ) ) class Program ( static void Main(string args) ( Console. WriteLine("Enter radius: "); string radius = Console.ReadLine(); MyMathOperation = new MyMathOperation ( r = double.Parse(radius) );

Using parameters

When you call a method, you can pass one or more values ​​to it. The value passed to the method is called argument. And the variable receiving the argument is called a formal parameter, or simply parameter. Parameters are declared in parentheses after the method name. The syntax for declaring parameters is the same as for variables. And the scope of parameters is the body of the method. Except for special cases of passing arguments to a method, parameters act just like any other variables.

In general, parameters can be passed to a method either by value or by reference. When a variable is passed by reference, the called method receives the variable itself, so any changes it makes within the method will remain in effect after the method completes. But if a variable is passed by value, the called method receives a copy of that variable, which means that any changes to it will be lost when the method exits. For complex data types, passing by reference is more efficient due to the large amount of data that must be copied when passing by value.

Let's look at an example:

Using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 ( class myClass ( public void someMethod(double myArr, int i) ( myArr = 12.0; i = 12; ) ) class Program ( static void Main(string args) ( double arr1 = ( 0, 1.5, 3.9, 5.1 ) ; int i = 0; Console.WriteLine("Array arr1 before calling the method: "); foreach (double d in arr1) Console.Write("(0)\t",d); = (0)\n",i); Console.WriteLine("Calling the someMethod method..."); myClass ss = new myClass(); ss.someMethod(arr1,i); Console.WriteLine("Array arr1 after method call:"); foreach (double d in arr1) Console.Write("(0)\t",d); Console.WriteLine("\nVariable i = (0)\n",i); Console.ReadLine (); ) ) )

Methods in C Sharp | C#

Methods are written code that is used many times (called many times). And to simplify the program code, using the method is very important. Method is a new word in the C Sharp language, the old word is function.

The methods are logical if this code is executed more than 2 times. Then it’s easier to declare the name of the method, what values ​​it accepts, and write code that would execute correctly for all the values ​​that the method accepts.

In order to declare methods in C#, you need to write the following:

RETURN_VALUE_TYPE FUNCTION_NAME (VARIABLES) (METHOD_CODE)

If you don’t need to return something, then you can write in RETURN_VALUE_TYPE - void .

1. A function that does not return a value and does not accept arguments:

void printError()
{
Console .Write("Error! Press Key..." );
Console .ReadKey();
}

2. A function that does not return a value, but takes an argument:

void printError(string s)
{
Console .Write("Error! " + s + "Press Key..." );
Console .ReadKey();
}

3. A function that does not return a value, but accepts arguments:

void printError(string s, int i)
{
Console .Write("Error! " + s + " " + i + "Press Key..." );
Console .ReadKey();
}

3. A function that returns values ​​and takes arguments:

char shifr(char x, int shifr)
{
x = (char)(x + shifr);
return x;
}

Here is an example of a program using methods: working with methods...

You can also set the protection level for the method: private, public.

Eg:

private char shifr(char x, int shifr)
{
x = (char)(x + shifr);
return x;
}

public char shifr(char x, int shifr)
{
x = (char)(x + shifr);
return x;
}