I am here to continue the series related to .NET interview preparation. Today we will discuss the common questions related to .NET operators and present the answers in an easy way.
So let’s takethe questions one by one.
1. What’s sizeof operator and how to use it?
Answer:
sizeof operator is used to return the size of any data type allocated by CLR in bytes.
For example,
- Console.Title = "C# Operator demo";
-
- var size = sizeof(int);
-
- Console.WriteLine("Size of type in bytes is: {0}", size);
Output:
Please note that, to obtain size of built-in types such as int, char, float, bool, decimal, sizeof can directly be used however for other types such as structs, enum and pointer types it can be used only in unsafe code blocks as following.
- struct EmployeeStruct
-
- {
-
- int empId;
-
- int salary;
-
- }
-
- public class Program
-
- {
-
- static void Main()
-
- {
-
- Console.Title = "C# Operator demo";
-
- int size = 0;
-
- unsafe
-
- {
-
- size = sizeof(EmployeeStruct);
-
- }
-
- Console.WriteLine("Size of type in bytes is: {0}", size);
-
- }
-
- }
Output:
Just to add that to enable unsafe compilation, you need to check the “Allow unsafe code” check box in project properties -> Build tab. Also please don’t get confused with Marshal.SizeOf Method because it returns the size after marshaling and that may not be the same as allocated by CLR.
2. What’s the similarity and difference between typeof and GetType?
Answer:
The similarity between typeof and GetType is that both return System.Type instance. However the difference is in their uses.
typeof is used to obtain the type at compile time and the operand of typeof is always a type directly whereas GetType is used to know the type of information at run time and it can be used individually at the objects.
GetType can also be used with expressions as it calculates the type at runtime. Example is as follows.
- class MyClass
- {
- public string Name
- {
- get;
- set;
- }
- }
- public class Program
- {
- static void Main()
- {
- Console.Title = "C# Operator demo";
- Console.WriteLine("Type is: {0}", typeof(int));
- Console.WriteLine("Type is: {0}", typeof(float));
- Console.WriteLine("Type is: {0}", typeof(bool));
- Console.WriteLine("Type is: {0}", typeof(char));
- MyClass obj = new MyClass();
- Console.WriteLine("Type is: {0}", obj.GetType());
- }
- }
Output:
3. Difference between is and as operator in C#.
Answer:
You may refer to my blog as follows for the same.
I hope you liked the article. I look forward to your comments/suggestions.