Usage of [ ] and () Operators in C# (C Sharp)C# provides
a wide set of operators of which [ ] operator and ( ) operators will be
discussed in this article. Each of these operators performs multiple operations
as discussed below.
( ) Operator: ( ) operator serves two different purposes. They are listed below: Decides
the order of precedence As already mentioned, C# has a wide set of operators. When multiple operators are used on an expression, then in what order will they be evaluated? For that C# has predefined rules for the order of precedence. For example, in arithmetic operators *, / takes more precedence over +, - operators. When your expression has * and + operators, * takes more precedence over + operator. If you want to change the precedence, you can use ( ) operator. Here is an example to demonstrate it: public class
sampleClass { Output of this code will be: result1 = 210 result2 = 600 In the first expression, 5*40 will be evaluated first and 10 will be added to the result. But in second expression you have changed the order of precedence using ( ) operator. You evaluate 10+5 first and to the result 15 you multiply 40. ( ) operator is also used to perform explicit casting termed as type conversion. C# permits automatic type conversion from certain data type to another. For example you can convert integer to double. That doesnt have any data loss and can happen without any casting. But when you try to convert from double to integer, there are chances of data loss. Hence if you directly assign double to integer you will end up in error. If you want to perform such conversions without ending up in error, then you can do it using ( ) operator as shown below: public class
sampleClass { Output of this code will be: Value of var2 = 100 [ ] Operator: [ ] operator is also used to perform different operations: In
Arrays If you want to use arrays in your code, you can do it only using [ ] operator. Right from declaration, initialization and even for accessing arrays you have to use [ ] operator. Here is an example to demonstrate it: class sampleClass
{ In this example, you use [ ] operator to do the following: To
declare a one dimensional integer array: int[ ] intArray [ ] operator can also be used with indexers. To know how [ ] operator is used in indexers, consider the following example: public class
sampleClass { Output of this code will be: value1, value2 In this example, you create an alternative way of accessing two dimensional array elements using [ ] operator. You can also use [ ] operator to specify attributes as shown in the example below:
It is also used in unsafe code context when you use pointers to access arrays, as shown in the example below: class sampleClass
{
|