ref etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
ref etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

7 Mayıs 2018 Pazartesi

ref Anahtar Kelimesi - Return Type

Giriş
C# 7 ile referans dönmek mümkün.Açıklaması şöyle.
You can only return refs that are “safe to return”: Ones that were passed to you, and ones that point into fields in objects.
array dönülebilir. Açıklaması şöyle.
Returning a local int variable instead of an array is not possible. int is a value type, and thus the variable gets out of scope at the end of the method, and thus a reference to it cannot be returned. That’s different with an array. An array is a reference type, and the array is allocated on the heap. An int within the array can be returned with the ref keyword.
Örnek - int
Şöyle yaparız.
public ref int Find(int number, int[] numbers)
{
  for (int i = 0; i < numbers.Length; i++)
  {
    if (numbers[i] == number)
    {
      return ref numbers[i]; // return the storage location, not the value
    }
  }
  throw new IndexOutOfRangeException($"{nameof(number)} not found");
}
Örnek - array
Şöyle yaparız.
public ref string Find (int index)
{
  string[] array = { "a", "b", "c", "d" };
  return ref array[index]; 
}
Örnek - struct
Şöyle yaparız.
// This size is 128 bytes, which is 2 or 4x larger than the size of a reference
public struct Coord                                 
{
    public long X, Y;
}

private Coord myCoord;

// This will return the Coord by value, meaning copying the full 128 bytes
public Coord GetCoordValue() => myCoord;          

// This will return the Coord by reference, meaning copying only 32 or 64 bytes
public ref readonly Coord GetCoordRef() => ref myCoord;      

8 Ocak 2018 Pazartesi

ref Anahtar Kelimesi

ref parametre
Açıklaması şöyle. ref parametreye metodu çağırmadan önce değer atanması gerekir.
An argument that is passed to a ref parameter must be initialized before it is passed. This differs from out parameters, whose arguments do not have to be explicitly initialized before they are passed. For more information, see out.
Şöyle yaparız.
public void TestRef(ref string n)
{
  ...
}
Çağırmak için şöyle yaparız.
string name = "Hello";
TestRef(ref name)
ref ve overload
Elimizde iki metod olsun.
public static void Func(int i)
{
  ...
}
public static void Func(ref int i)
{
  ...
}
        int a = 9;
        Func(ref a);
ref metod yine ref ile çağrılmak zorunda olduğu için karışıklık çıkmaz. Şöyle yaparız.
int a = 9;
Func(ref a);
ref return type
ref return type yazısına taşıdım.