달력

5

« 2024/5 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
2016. 11. 14. 21:00

Operators 프로그래밍/C#2016. 11. 14. 21:00


https://msdn.microsoft.com/en-us/library/6a71f45d.aspx



?? Operator


Updated: July 20, 2015

The ?? operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand.

A nullable type can represent a value from the type’s domain, or the value can be undefined (in which case the value is null). You can use the ??operator’s syntactic expressiveness to return an appropriate value (the right hand operand) when the left operand has a nullible type whose value is null. If you try to assign a nullable value type to a non-nullable value type without using the ?? operator, you will generate a compile-time error. If you use a cast, and the nullable value type is currently undefined, an InvalidOperationException exception will be thrown.

For more information, see Nullable Types.

The result of a ?? operator is not considered to be a constant even if both its arguments are constants.

    class NullCoalesce
    {
        static int? GetNullableInt()
        {
            return null;
        }

        static string GetStringValue()
        {
            return null;
        }

        static void Main()
        {
            int? x = null;

            // Set y to the value of x if x is NOT null; otherwise,
            // if x = null, set y to -1.
            int y = x ?? -1;

            // Assign i to return value of the method if the method's result
            // is NOT null; otherwise, if the result is null, set i to the
            // default value of int.
            int i = GetNullableInt() ?? default(int);

            string s = GetStringValue();
            // Display the value of s if s is NOT null; otherwise, 
            // display the string "Unspecified".
            Console.WriteLine(s ?? "Unspecified");
        }
    }





?: Operator


Updated: July 20, 2015

The conditional operator (?:) returns one of two values depending on the value of a Boolean expression. Following is the syntax for the conditional operator.

condition ? first_expression : second_expression;  

The condition must evaluate to true or false. If condition is truefirst_expression is evaluated and becomes the result. If condition is falsesecond_expression is evaluated and becomes the result. Only one of the two expressions is evaluated.

Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.

You can express calculations that might otherwise require an if-else construction more concisely by using the conditional operator. For example, the following code uses first an if statement and then a conditional operator to classify an integer as positive or negative.

  
int input = Convert.ToInt32(Console.ReadLine());  
string classify;  
  
// if-else construction.  
if (input > 0)  
    classify = "positive";  
else  
    classify = "negative";  
  
// ?: conditional operator.  
classify = (input > 0) ? "positive" : "negative";  
  

The conditional operator is right-associative. The expression a ? b : c ? d : e is evaluated as a ? b : (c ? d : e), not as (a ? b : c) ? d : e.

The conditional operator cannot be overloaded.

    class ConditionalOp
    {
        static double sinc(double x)
        {
            return x != 0.0 ? Math.Sin(x) / x : 1.0;
        }

        static void Main()
        {
            Console.WriteLine(sinc(0.2));
            Console.WriteLine(sinc(0.1));
            Console.WriteLine(sinc(0.0));
        }
    }
    /*
    Output:
    0.993346653975306
    0.998334166468282
    1
    */





Null-conditional Operators


Updated: July 20, 2015

Used to test for null before performing a member access (?.) or index (?[) operation. These operators help you write less code to handle null checks, especially for descending into data structures.

int? length = customers?.Length; // null if customers is null   
Customer first = customers?[0];  // null if customers is null  
int? count = customers?[0]?.Orders?.Count();  // null if customers, the first customer, or Orders is null  
  

The last example demonstrates that the null-condition operators are short-circuiting. If one operation in a chain of conditional member access and index operation returns null, then the rest of the chain’s execution stops. Other operations with lower precedence in the expression continue. For example, E in the following always executes, and the ?? and == operations execute.

A?.B?.C?[0] ?? E  
A?.B?.C?[0] == E  
  

Another use for the null-condition member access is invoking delegates in a thread-safe way with much less code. The old way requires code like the following:

var handler = this.PropertyChanged;  
if (handler != null)  
    handler(…)  
  

The new way is much simpler:

PropertyChanged?.Invoke(e)  
  

The new way is thread-safe because the compiler generates code to evaluate PropertyChanged one time only, keeping the result in temporary variable.

You need to explicitly call the Invoke method because there is no null-conditional delegate invocation syntax PropertyChanged?(e). There were too many ambiguous parsing situations to allow it.

For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

For more information, see the Visual Basic Language Reference.




=> Operator


Updated: July 20, 2015

The => token is called the lambda operator. It is used in lambda expressions to separate the input variables on the left side from the lambda body on the right side. Lambda expressions are inline expressions similar to anonymous methods but more flexible; they are used extensively in LINQ queries that are expressed in method syntax. For more information, see Lambda Expressions.

The following example shows two ways to find and display the length of the shortest string in an array of strings. The first part of the example applies a lambda expression (w => w.Length) to each element of the words array and then uses the Min<TSource> method to find the smallest length. For comparison, the second part of the example shows a longer solution that uses query syntax to do the same thing.

string[] words = { "cherry", "apple", "blueberry" };  
  
// Use method syntax to apply a lambda expression to each element  
// of the words array.   
int shortestWordLength = words.Min(w => w.Length);  
Console.WriteLine(shortestWordLength);  
  
// Compare the following code that uses query syntax.  
// Get the lengths of each word in the words array.  
var query = from w in words  
            select w.Length;  
// Apply the Min method to execute the query and get the shortest length.  
int shortestWordLength2 = query.Min();  
Console.WriteLine(shortestWordLength2);  
  
// Output:   
// 5  
// 5  

The => operator has the same precedence as the assignment operator (=) and is right-associative.

You can specify the type of the input variable explicitly or let the compiler infer it; in either case, the variable is strongly typed at compile time. When you specify a type, you must enclose the type name and the variable name in parentheses, as the following example shows.

int shortestWordLength = words.Min((string w) => w.Length);  

The following example shows how to write a lambda expression for the overload of the standard query operator Enumerable.Where<TSource> that takes two arguments. Because the lambda expression has more than one parameter, the parameters must be enclosed in parentheses. The second parameter, index, represents the index of the current element in the collection. The Where expression returns all the strings whose lengths are less than their index positions in the array.

static void Main(string[] args)  
{  
    string[] digits = { "zero", "one", "two", "three", "four", "five",   
            "six", "seven", "eight", "nine" };  
  
    Console.WriteLine("Example that uses a lambda expression:");  
    var shortDigits = digits.Where((digit, index) => digit.Length < index);  
    foreach (var sD in shortDigits)  
    {  
        Console.WriteLine(sD);  
    }  
  
    // Output:  
    // Example that uses a lambda expression:  
    // five  
    // six  
    // seven  
    // eight  
    // nine  
}  




-> Operator


Updated: July 20, 2015

The -> operator combines pointer dereferencing and member access.

An expression of the form,

x->y  

(where x is a pointer of type T* and y is a member of T) is equivalent to,

(*x).y  

The -> operator can be used only in code that is marked as unsafe.

The -> operator cannot be overloaded.

    // compile with: /unsafe

    struct Point
    {
        public int x, y;
    }

    class MainClass12
    {
        unsafe static void Main()
        {
            Point pt = new Point();
            Point* pp = &pt;
            pp->x = 123;
            pp->y = 456;
            Console.WriteLine("{0} {1}", pt.x, pt.y);
        }
    }
    /*
    Output:
    123 456
    */

















'프로그래밍 > C#' 카테고리의 다른 글

C# Keywords - Types  (0) 2016.12.29
helpful classes  (0) 2016.11.24
IEnumerable Interface  (0) 2016.11.14
Predicate<T> Delegate  (0) 2016.10.18
DateTime, TimeSpan  (0) 2016.10.12
:
Posted by 지훈2