TopMenu

C# keywords rarely known but frequently asked in Interview Questions

There are few words that we rarely use in day to day C# practices[I’m focusing readers who are beginners]. But I’ve seen them in either online exams or other IT quiz shows So I came to write something about those untouched keywords. Below is the list of these keywords

  • Implicit
  • Explicit
  • Volatile
  • Checked
  • Unchecked
  • Const vs ReadOnly [The most frequently asked Interview question for C# programmer]

Lets get to know about them which one is used where and when:

Implicit

The implicit keyword is used to declare an implicit user-defined type conversion operator. Implicit conversion operators can be called implicitly, without being specified by explicit casts in the source code. It eliminates unnecessary casts, implicit conversions can improve source code readability.

The below example you can see we’ve a CustomType that takes Integer value as its initializing value and after defining the Implicit operator It becomes directly castable to int.

image


However, because implicit conversions can occur without the programmer's specifying them, care must be taken to prevent unpleasant surprises. In general, implicit conversion operators should never throw exceptions and never lose information so that they can be used safely without the programmer's awareness.

Explicit

As I mentioned sometimes implicit conversion can surprise you as it can go unnoticed. So in case you want to enforce an casting to be explicit then Explicit keyword is there. Again The explicit keyword is used to declare an explicit user-defined type conversion operator.

class MyType
    {
        public static explicit operator MyType(int i)
        {
            // code to convert from int to MyType
        }
    }

Unlike the Implicit it enforces the explicit cast to mention when a type is declared with conversion operator.

image

Volatile:

Volatile is kept under the category of Modifiers. The volatile keyword indicates that a field can be modified in the program by something such as the operating system, the hardware, or a concurrently executing thread.

Syntax:

public volatile int i;

Behavior: The system always reads the current value of a volatile object at the point it is requested, even if the previous instruction asked for a value from the same object. Also, the value of the object is written immediately on assignment. And due to such behavior  volatile modifier is usually used for a field that is accessed by multiple threads without using the lock statement to serialize access. Using the volatile modifier ensures that one thread retrieves the most up-to-date value written by another thread.

The type of a field marked as volatile is restricted to the following types:

  • Any reference type.
  • Any pointer type (in an unsafe context).
  • The types sbyte, byte, short, ushort, int, uint, char, float, bool.
  • An enum type with an enum base type of byte, sbyte, short, ushort, int, or uint.

 

Checked and Unchecked:

Before we start I want to show you some code:

public static void Main() {     short x = 32767;   // Max short value     short y = 32767;     int z = 0;     //perform the sum and try cast it back to short before assigning     z = (short)(x + y);     Console.WriteLine("Checked output value is: {0}", z);     Console.Read(); }

Output:

image?????????????????????

Are you expecting this output in you application or Program. Better you throw an exception if you system is dealing with sensitive data. If you think so.. then use Checked.

Syntax:

checked(expression)

Now modify the above code like this:

try {     z = checked((short)(x + y)); } catch (System.OverflowException e) {     System.Console.WriteLine(e.ToString()); }

Now see the output:

image

Important Note: In a checked context, if an expression produces a value that is outside the range of the destination type, the result depends on whether the expression is constant or non-constant. Constant expressions cause compile time errors, while non-constant expressions are evaluated at run time and raise exceptions.

Similarly if you want to Skip such check always if your application or logic is flexible and ineffective by the resulting values then use unchecked.

Syntax:

unchecked (expression)

int z = unchecked((short)(x + y));

Output would be the same as we had without using checked.

image

if neither checked nor unchecked is used, a constant expression uses the default overflow checking at compile time, which is checked. Otherwise, if the expression is non-constant, the run-time overflow checking depends on other factors such as compiler options and environment configuration.

const vs readonly

So here we are at Interview Question. I’m sure these words are mostly used in code. So I’m not going show any demo for their use but to discuss some interesting answers that your interview would like Winking smile.

const value type

  • must be initialized
  • initialization must be at compile time

A constant member is defined at compile time and cannot be changed at runtime. Constants are declared as a field, using the const keyword and must be initialized as they are declared.

Constants must be a value type (sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool), an enumeration, a string literal, or a reference to null.

readonly value type

  • It can use default value, without initializing
  • initialization can be at run time

  • can be initialized either at the declaration or in a constructor

A read only member is like a constant in that it represents an unchanging value. The difference is that a readonly member can be initialized at runtime, in a constructor as well being able to be initialized as they are declared.

I hope this post provide some quick and useful information to those who are beginners in C#.

2 comments:

  1. Firstly, it never ceases to amaze me that people ask syntax questions in interviews :-)

    Anyway, I thought I would add some concepts that might further clarify some of these points.

    Volatile, you definition is good. But to add further, in practice I believe the root cause of the problem it alleviates is the cpu cache having a stale value, eg it alleviates the case where one thread updates the value, but another thread gets the stale value from the cache.

    Const vs Readonly. Correct, compile time vs runtime. A real example of this scenario is where you have a multi-assembly application. If a class library (A) in one assembly exposes a const that is referenced in another assembly (B), the const value is compiled into the assembly B as a literal. So, if you released a new version of assembly A without recompiling Assembly B and the const value was changed, that changed const would not be reflected in assembly B as it will still have the original value from when it was compiled.

    ReplyDelete
  2. Great article! Thanks!

    And @above comment... I did not know that about the consts referred in other assemblies!!

    - Raman (Nagarro)

    ReplyDelete