Master C# Operators: Top 12 Interview Questions

Operators’ questions are trendy for C# job interviews. Usually, the interviewers ask the juniors for quizzes regarding operators, but you can also receive these types of questions. So let’s start to prepare with some questions:

What will be printed?

Console.WriteLine('a'+'b'+'c');

Answer: 294, because the summation of chars will give you a number. First, the chars are converted to the ASCII code. For example, the ASCII code of the letter a is 97. You don’t need to know the numeric code, but remember that you don’t concatenate chars using the sign plus.

What will be printed?

Console.WriteLine("A"+"B"+"C");

Answer: ABC

In this case, we used double quotes to deal with strings.

What will be printed?

static void AddSign(string nume)
{
    nume += "TEST";
}


static void Main()
{
    string carName = "Mercedes";
    AddSign(carName);
    Console.WriteLine(carName);
}

The above program will print Mercedes.

A string variable is a reference type, and it’s immutable, so we pass the reference when we call the method. Inside that method, we change the reference to something else. In this case, the variable from the method will point to another string. When the execution returns to the main, the old reference is not changed.

How do you change the above code to print MercedesTest?

static void AddSign(string ref nume)
{
    nume += "TEST";
}


static void Main()
{
    string carName = "Mercedes";
    AddSign(carName);
    Console.WriteLine(ref carName);
}

We use the ref keyword.

 What happens if you sum the maximum integer value with 1?

int x = int.MaxValue;
int y = x + 1;
Console.WriteLine(y); // it will print int.MinValue

It shows the minimum value of the integer. The explanation is that it changes the first bit, which specifies the sign of the number.

How do you fix the above code to throw an exception if the value of the integer is exceeded?

To solve this problem, we should use the checked block.

checked
{
    int x = int.MaxValue; int y = x + 1; Console.WriteLine(y); // it will throw an OverflowException
}

What is the difference between the is and as operators in C#?

The is operator returns true if a given object is a particular type, while the as operator returns the object if it is the given type.

object obj = "Hello world";

if (obj is string)
{
    string str = (string)obj;
    Console.WriteLine(str); // Output: Hello world
}

What does sizeof operator do?

The sizeof operator returns the storage needed for the given type. It can be used only in an unsafe block.

How do you use the null-coalescing operator (??) in C#?

In C#, the null-coalescing operator returns the left part if the value is not null. Otherwise, it returns the part from the right.

Car car = new Car() { Name = "BMW" };
Console.WriteLine(car.Name ?? "Unknown");// prints "BMW"
car = null;
Console.WriteLine(car?.Name ?? "Unknown"); // prints "Unknown"

What’s the difference between == operator and the Equals method?

The == operator compares the values of two objects to see if they are equal. In case you have reference types, the == operator returns true only if the objects point to the same location in the memory. Even if the properties inside the object are the same, by default the == operator will compare the reference of the objects.

int a = 5;
int b = 5;

// Using '==' operator
bool isEqualOperator = (a == b); // true

// Using 'Equals' method
bool isEqualMethod = a.Equals(b); // true

The equal method is a virtual method defined in the Object class. This can be overridden in your classes to provide custom equality comparison.

class Car
{
    public string Name { get; set; }

    public Car(string name)
    {
        Name = name;
    }
}

internal class Program
{
    static void Main(string[] args)
    {
        Car car1 = new Car("Mercedes");
        Car car2 = new Car("Mercedes");
        Console.WriteLine(car1==car2); // false
    }
}
class Shop
{
    public string Name { get; set; }
    public Shop(string name)
    {
        Name = name;
    }

    public override bool Equals(object? obj)
    {
        if (obj == null) return false;
        if (obj == this) return true;
        Shop other = obj as Shop;
        if (other == null) return false;
        return other.Name == Name;
    }
}

internal class Program
{
    static void Main(string[] args)
    {
        Shop shop1 = new Shop("Tesco");
        Shop shop2 = new Shop("Tesco");
        Console.WriteLine(shop1.Equals(shop2)); // true
    }
}

In the first example, we used the == operator. This operator compares if the objects have the same reference. In the second example, we defined the Equal method, which is why it returns true.

Write an example of the ternary operator

The ternary operator is used a lot in many programming languages like JavaScript, Java, or C#. It is a way to create an inline if-else statement.

int x = 2;
int y = x==2 ? 1 : x;  // this translates to set variable y to 1 if x is equal to 2, else return x.
Console.WriteLine(y); // prints 1

Resolve exercises using bitwise & and | operators

This exercise is pretty simple if you know how to convert decimal numbers to binary. Take a look here if you don’t remember.

The AND  operator will compare the corresponding bits for each number. If both are 1,  then the result is 1, otherwise is 0.

In the case of the OR operator(|), if the corresponding bits are 1 or if at least one of the bit is 0, then the result is 1, otherwise is 0.

static void Main(string[] args)
{
    int x = 9; // 1001
    int y = 10; //1010
    Console.WriteLine(x & y); // 1000 => 8, because only the first bit is 1, for both 1011 and 1010
    Console.WriteLine(x | y); // 1011 => 11, 
}

Checked and unchecked keywords in C#

Checked and unchecked keywords are used for arithmetic operations. Have you ever thought about what happens when you add ‘int32.MaxValue’ to 1? The result is the value of int32.MinValue, because each int has the first bit that mentions the sign of the number. When you add 1, to the maximum value, the first bit will change.

To ensure you don’t have this type of situation, you can use the checked keyword. If an overflow happens, then the code will throw an exception.

int maxValue = int.MaxValue;

checked
{
    int resultChecked = maxValue + 1; // Throws OverflowException
}

If you are interested in more interview questions for .NET, you can check this article:

Leave a Comment