Operators
There are many different kinds of operators defined in C#. The operators can also be overloaded to change their meaning when applied to user-defined type.
Most common operators are (==, !=, <, >, &, |) and generally used with enumeration types.
Primary Operators
These are the highest precedence operators.
(Dot).Operator (x.y)
Composed of 2 primary expressions: member-lookup and method call. It is used for member access such as access specific method within the framework.
-- Accessing Console class in System namespace System.Console.WriteLine("Hello World"); class Simple { public int a; public void b() {} } --Initiate Simple s = new Simple(); -- Accessing the members s.a = 6; --asign to field a s.b(); -- invoke member function b;
Null-conditional Operators (x?.y)
Returns null if the left-hand operand is null. It tests null before performing member access. In a chain conditional operation if operation returns null then rest execution stops. Null-conditional operator is useful when invoking delegates in a thread-safe with less code.
-- int? length - can be null or number -- return null if customers is null or access the Length property int? length = customers?.Length; -- return null if array is empty or access the array objects Customer first = customer?[0] -- return null if customers, first customer or Orders is null int? count = customers?[0]?.Orders?.Count(); -- operations with lower precedence will continue to operate A?.B?.C?[0] ?? E A?.B?.C?[0] == E -- using with thread PropertyChanged?.Invoke(e);
Null-conditional Index Access (x?[y])
Returns null if the left-hand operand is null
Customer first = customers?[0]; -- null if customers is null
Function Invocation f(x)
It is use to specify the order of operation. It cannot be overloaded.
1. Specifiy casts or type conversion
double x = 23.6; int a; a = (int)x;
2. Invoke methods or delegates
TestMethod();
Aggregate Object Indexing a[x]
Used for arrays, indexers and attributes or with pointers. Out of range exception if array is out of range.
int[] array; -- array of int array = new int[50] -- array for 50 element --access array element array[4];
Square brackets are also used to specify Attributes:
// using System.Diagnostics; [Conditional("DEBUG")] void TraceMethod() {}
Postfix Increment (x++)
Returns the value of x by incrementing its operand by 1. It can appear before or after the variable.
prefix increment – result return after increment
postfix increment – result return before increment
double x = 2.5; Console.WriteLine(++x); -- 3.5 x = 1.5; Console.WriteLine(x++); -- 1.5 Console.WriteLine(x); -- 2.5
Postfix Decrement (x–)
Returns the decrement value by the operand. Can appear before or after the variable.
double x = 2.5; Console.WriteLine(--x); -- 1.5 x = 1.5; Console.WriteLine(x--); --1.5 Console.WriteLine(x); -- 0.5
Type Instantiation (new)
Create object and invoke constructors also create instances of anonymous types. It can be used to invoke the default constructor for value types. Cannot be overloaded. Remember not to declare default constructor for struct because every value type has a public constructor.
-- Class Class1 obj = new Class1(); -- anonymous object var query = from cust in customers select new { Name = cust.Name, Address = cust.PrimaryAddress }; -- value types int i = new int();
typeof()
Returns the System.Type object for a particular object. Can be used with open generics types.
System.Type type = typeof(int);
For run-time expression
int i = 0; System.Type type = i.GetType(); int radius = 3; Console.WriteLine("Area = {0}", radius * radius * Math.PI); Console.WriteLine("The type is {0}", (radius * radius * Math.PI).GetType() -- generic example string s = method.ReturnType.GetInterface (typeof(System.Collections.Generic.IEnumerable<>).FullName); public class Program { public int sampleMember; public void SampleMethod() {} public static void Main(string[] args) { Type t = typeof(Program); // Alternatively, you could use // ExampleClass obj = new ExampleClass(); // Type t = obj.GetType(); Console.WriteLine("Methods:"); System.Reflection.MethodInfo[] methodInfo = t.GetMethods(); foreach (System.Reflection.MethodInfo mInfo in methodInfo) Console.WriteLine(mInfo.ToString()); Console.WriteLine("Members:"); System.Reflection.MemberInfo[] memberInfo = t.GetMembers(); foreach (System.Reflection.MemberInfo mInfo in memberInfo) Console.WriteLine(mInfo.ToString()); } }
Checked
Enables overflow checking for integer operations and conversions
int ten = 10; int i2 = 2147483647 + ten; Console.WriteLine(i2); Console.WriteLine(checked(2147483647 + ten)); checked { int i3 = 2147483647 + ten; Console.WriteLine(i3); }
Unchecked
Disables overflow checking for integer operations. This is the default compiler behavior.
unchecked { int1 = 2147483647 + 10; } int1 = unchecked(ConstantMax + 10);
Default Value Expression
Produces the default value of type T, null for references, 0 for numeric types.
var s = default(string); var d = default(dynamic); var i = default(int); var n = default(int?); // n is a Nullable int where HasValue is false.
It can be applied in the following places:
– Variable initializer
– Variable assignment
– Declaring the default value for an optional parameter
– Providing the value for a method call argument
– Return statement (or expression in an expression bodied member)
Delegate (Anonymous Methods)
Declares and returns a delegate instance.
// Create a delegate. delegate void Del(int x); // Instantiate the delegate using an anonymous method. Del d = delegate(int k) { /* ... */ };
It is an error to have jump statements such as continue or break.
sizeof
Returns the size in bytes for an unmanaged type such as enum, pointer,user-defined structs.
-> Pointer
Pointer dereferencing combined with member access.Used in unsafe environment.