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
- 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:
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.
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.
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.
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.
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.
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:
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.
Now modify the above code like this:
Now see the output:
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.
Output would be the same as we had without using checked.
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 (
bool), an enumeration, a string literal, or a reference to
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#.
Firstly, it never ceases to amaze me that people ask syntax questions in interviews :-)ReplyDelete
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.
Great article! Thanks!ReplyDelete
And @above comment... I did not know that about the consts referred in other assemblies!!
- Raman (Nagarro)