ref va out metod parametrlari, ularning farqi, ishlatilishi C#

ref va out metod parametrlari, ularning farqi, ishlatilishi C#

ref va out kalit so’zlari yoramida metodga tashqaridan parameter berish mumkin. Metod ichida ref va out yordamida olingan parametrlar ustida bajarilgan amallar metodddan tashqarida bu parametrlarga ta’sir qiladi.

Masalan:
1)

using System;
class Program
{
    static void Main()
    {
	int val = 0;

	Example1(val);
	Console.WriteLine(val);// Natija: 0

	Example2(ref val);
	Console.WriteLine(val); // Endi val o’zgaruvchi qiymati 2

	Example3(out val);
	Console.WriteLine(val); // val= 3
    }

    static void Example1(int value)
    {
	value = 1;
    }

    static void Example2(ref int value)
    {
	value = 2;
    }

    static void Example3(out int value)
    {
	value = 3;
    }
}

Natija:

0
2
3
2)

class OutExample
{
    static void Method(out int myValue)
    {
        myValue = 44;
    }
    static void Main()
    {
        int value;
        Method(out value);// value=44
	Console.WriteLine(“value= ”,value);
    } 
}

Natija:
Value=44
3)

class RefExample
    {
        static void MethodForRef(ref int qiymat1, ref string name)
        {
            qiymat1 = qiymat1 + 44;
	     name += “name is”;
        }

        static void Main()
        {
            int val = 1;
            string nameValue = “Mansur”;

            MethodForRef(ref val, ref nameValue );
            Console.WriteLine(“nameValue =”, nameValue);
            Console.WriteLine(“val=”,val);
        }
    }

Natija:
nameValue = name is Mansur
val = 45

ref va out metod parametrlarining farqi
ref ni ishlatishda doimo o’zgaruvchiga boshlang’ich qiymat berish shart, out da esa shart emas!
4)

namespace TestingRefAndOut
{
    class Animal
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Animal myAnimal = new Animal();
            myAnimal.Name = "Fox"; myAnimal.Age = 2;
            Init(myAnimal);
            Console.WriteLine("1-holat: Name ={0} va Age={1} ",myAnimal.Name,myAnimal.Age);
            Init(ref myAnimal);
            Console.WriteLine("2-holat (Init metodi ref metod argumeti bilan ishlatilganda): Name={0} va Age={1} ",
                myAnimal.Name, myAnimal.Age);
            Console.ReadLine();
        }
        static void Init(Animal animal){
            Animal tempAnimal=new Animal()
            {
                Name = "Tiger", Age=5
            };
            animal = tempAnimal;
        }
        static void Init(ref Animal animal){
            Animal tempAnimal=new Animal()
            {
                Name = "Lion", Age=7
            };
            animal = tempAnimal;
        }
    }
}

Natija:

, ,

Нет комментариев