C# - Miscellaneous Operators



What are C# Miscellaneous Operators?

C# miscellaneous operators are special operators that don't come under arithmetic, logical, relational, or bitwise categories. These operators are basically used for type checking, null handling, and memory referencing.

List of C# Miscellaneous Operators

There are few other important operators including sizeof and ? : supported by C#.

Operator Description Example
sizeof() Returns the size of a data type. sizeof(int), returns 4.
typeof() Returns the type of a class. typeof(StreamReader);
& Returns the address of an variable. &a; returns actual address of the variable.
* Pointer to a variable. *a; creates pointer named 'a' to a variable.
? : Conditional Expression If Condition is true ? Then value X : Otherwise value Y
is Determines whether an object is of a certain type. If( Ford is Car) // checks if Ford is an object of the Car class.
as Cast without raising an exception if the cast fails. Object obj = new StringReader("Hello");

StringReader r = obj as StringReader;

Example of Miscellaneous Operators

using System;

namespace OperatorsAppl {

   class Program {
   
      static void Main(string[] args) {
         /* example of sizeof operator */
         Console.WriteLine("The size of int is {0}", sizeof(int));
         Console.WriteLine("The size of short is {0}", sizeof(short));
         Console.WriteLine("The size of double is {0}", sizeof(double));
         
         /* example of ternary operator */
         int a, b;
         a = 10;
         b = (a == 1) ? 20 : 30;
         Console.WriteLine("Value of b is {0}", b);

         b = (a == 10) ? 20 : 30;
         Console.WriteLine("Value of b is {0}", b);
         Console.ReadLine();
      }
   }
}

When the above code is compiled and executed, it produces the following result −

The size of int is 4
The size of short is 2
The size of double is 8
Value of b is 30
Value of b is 20

More Examples of Miscellaneous Operators

Example 1: Ternary Operator (?:)

The ternary operator is used to replace simple if-else conditions in a single line.

In the following example, we are using the ternary operator to check if the age is 18 or above and return either "Adult" or "Minor" accordingly.

using System;

class Program
{
    static void Main()
    {
        int age = 20;
        string result = (age >= 18) ? "Adult" : "Minor";

        Console.WriteLine(result);
    }
}

When the above code is compiled and executed, it produces the following result −

Adult

Example 2: Null-Coalescing Operator (??)

The null-coalescing operator (??) is very useful while dealing with variables having null values. This operator simply assigns a default value if the variable is null.

In the following example, we are assigning 100 to the variable if it is null using the null-coalescing operator.

using System;

class Program
{
    static void Main()
    {
        int? number = null;
        int result = number ?? 100; // If 'number' is null, assign 100

        Console.WriteLine(result);
    }
}

When the above code is compiled and executed, it produces the following result −

100

Example 3: Null-Coalescing Assignment (??=)

The ??= operator assigns a value only if the variable is null.

In the following example, we are using the null-coalescing assignment operator to assign a default message if the variable is null.

using System;

class Program
{
    static void Main()
    {
        string message = null;
        message ??= "Default Message"; // Assigns value only if message is null

        Console.WriteLine(message);
    }
}

When the above code is compiled and executed, it produces the following result −

Default Message

Example 4: Type Checking Operator (is)

The is operator checks if an object is of a certain type.

In the following example, we are using the 'is' operator to check if the given object is of type string.

using System;

class Program
{
    static void Main()
    {
        object obj = "Hello, World!";

        if (obj is string)
        {
            Console.WriteLine("obj is a string.");
        }
    }
}

When the above code is compiled and executed, it produces the following result −

obj is a string.

Example 5: Safe Type Casting (as)

The as operator performs type casting safely without throwing exceptions.

In the following example, we are using the 'as' operator to safely cast an object to a string.

using System;

class Program
{
    static void Main()
    {
        object obj = "Hello, C#";
        string str = obj as string;

        if (str != null)
        {
            Console.WriteLine("Safe casting successful: " + str);
        }
    }
}

When the above code is compiled and executed, it produces the following result −

Safe casting successful: Hello, C#

Example 6: Using sizeof to Get Data Type Size

The sizeof operator returns the size of a data type in bytes.

In the following example, we are using the 'sizeof' operator to determine the size of an integer type in bytes.

using System;

class Program
{
    static unsafe void Main()
    {
        Console.WriteLine("Size of int: " + sizeof(int) + " bytes");
    }
}

When the above code is compiled and executed, it produces the following result −

Size of int: 4 bytes

Use Cases

The following examples demonstrate the real-world use cases of miscellaneous operators in C#:

Example 7: Using ?? for Default Values in Web Forms

In the following example, we are using the null-coalescing operator to assign a default username if the user input is null.

using System;

class Program
{
    static void Main()
    {
        string userInput = null;
        string finalInput = userInput ?? "Default Username";

        Console.WriteLine("User: " + finalInput);
    }
}

When the above code is compiled and executed, it produces the following result −

User: Default Username

Example 8: Checking Object Type with is

In the following example, we are using the 'is' operator to check if the given object is an integer and retrieve its value if it is.

using System;

class Program
{
    static void Main()
    {
        object obj = 42;

        if (obj is int number)
        {
            Console.WriteLine("obj is an integer: " + number);
        }
    }
}

When the above code is compiled and executed, it produces the following result −

obj is an integer: 42

Best Practices

The following are the best practices while working with miscellaneous and type operators.

  • You should use ?: for concise conditional expressions.
  • You should use ?? and ??= to handle null values safely.
  • You should use is and as for runtime type checking and safe type casting.
  • You must avoid using sizeof with reference types.
  • You should use parentheses in ternary expressions for better clarity.
Advertisements