Rarely used keywords in CSharp but Frequently asked in discussions [Beginners]


There are a 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.

Implicit

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 a 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 Implicit, it enforces the explicit cast to mention when a type is declared with conversion operator.

Explicit

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 volatilemodifier 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:

Checked and Unchecked????????????????????

Are you expecting this output in you application or Program. Better 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:

Checked and Unchecked

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.

Checked and Unchecked

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.

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 areadonly 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#.

  

Up Next
    Ebook Download
    View all
    Learn
    View all