Monday, June 29, 2015

C# Nutshell Chapter 1-2 Basics

"==" makes a compile-time decision

int x = 1;
int y = 1;
x == y // true

object x = 1;
object y = 1;
x == y // false; referential equality from object's == operator

"Equals" is resolved at runtime, according to the object's actual type

object x = 1;
object y = 1;
x.Equals(y);  //true


object class static helper method providing null-safe equality comparision

object x = 3, y = 3;
Console.WriteLine (object.Equals (x, y)); // True
x = null;
Console.WriteLine (object.Equals (x, y)); // False
y = null;
Console.WriteLine (object.Equals (x, y)); // True

implicitly assigned default value

static void Main()
{
int x;
Console.WriteLine (x); // Compile-time error
}


class Test
{
static int x;
static void Main() { Console.WriteLine (x); } // 0
}

"ref" and "out" keywords


  • "ref" - pass in as reference rather than value
  • "out" - no need to be assigned before going into the function, but must be assigned before comes out of the function. 
  • both "ef"and "out" are passed in by reference

"params" modifier

The params parameter modifier may be specified on the last parameter of a method
so that the method accepts any number of parameters of a particular type.

static int Sum (int a, int b, params int[] ints)
{
Console.WriteLine(a);
Console.WriteLine(b);
int sum = 0;
for (int i = 0; i < ints.Length; i++)
sum += ints[i]; // Increase sum by ints[i]
return sum;
}

Optional parameters

void Foo (int x = 23) { Console.WriteLine (x); }
Foo(); // 23

Mandatory parameters must occur before optional parameters in both the method declaration and the method call public method that’s called from another assembly requires recompilation of both assemblies.

void Foo (int x = 0, int y = 0) { Console.WriteLine (x + ", " + y); }
void Test()
{
Foo(1); // 1, 0
}

Named arguments

Rather than identifying an argument by position, you can identify an argument by
name.

void Foo (int x, int y) { Console.WriteLine (x + ", " + y); }
void Test()
{
Foo (y:2, x:1); // 1, 2
}

Named arguments are particularly useful in conjunction with optional parameters.
For instance, consider the following method:
void Bar (int a = 0, int b = 0, int c = 0, int d = 0) { ... }
We can call this supplying only a value for d as follows:
Bar (d:3);




















No comments:

Post a Comment