Guide to the Language


Download 2 Mb.
Pdf ko'rish
bet68/78
Sana30.04.2023
Hajmi2 Mb.
#1414515
TuriGuide
1   ...   64   65   66   67   68   69   70   71   ...   78
Bog'liq
C sharp

 Calling Generic Methods
The generic method is now finished. To call it, the desired type argument 
needs to be specified in angle brackets before the method arguments.
int a = 0, b = 1;
Swap(ref a, ref b);
In this case, the generic method may also be called as if it were a 
regular method, without specifying the type argument. This is because the 
compiler can automatically determine the type since the generic method’s 
parameters use the type parameter. However, if this was not the case, or 
to use another type argument than the one the compiler would select, the 
type argument would then need to be explicitly specified.
Chapter 28 GeneriCs


161
Swap(ref a, ref b);
Whenever a generic is called for the first time during runtime, a 
specialized version of the generic will be instantiated that has every 
occurrence of the type parameter substituted with the specified type 
argument. It is this generated method that will be called and not the 
generic method itself. Calling the generic method again with the same type 
argument will reuse this instantiated method.
Swap(ref a, ref b); // create & call Swap
Swap(ref a, ref b); // call Swap
When the generic method is called with a new type, another 
specialized method will be instantiated.
long c = 0, d = 1;
Swap(ref c, ref d); // create & call Swap
 Generic Type Parameters
A generic can be defined to accept more than one type parameter just by 
adding more of them between the angle brackets. Generic methods can 
also be overloaded based on the number of type parameters that they 
define.
static void Dummy() {}
static void Dummy() {}
Chapter 28 GeneriCs


162
 Default Value
When using generics, one issue that may arise is how to assign a default 
value to a type parameter since this value depends on the type. The 
solution is to use the default keyword followed by the type parameter 
enclosed in parentheses. This expression will return the default value no 
matter which type parameter is used.
static void Reset(ref T a)
{
a = default(T);
}
Default expressions were enhanced in C# 7.1. As of this version, the 
type supplied to default may be omitted when the compiler can infer the 
type based on the context.
static void Reset(ref T a)
{
a = default; // same as default(T)
}

Download 2 Mb.

Do'stlaringiz bilan baham:
1   ...   64   65   66   67   68   69   70   71   ...   78




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling