Tech Point Fundamentals

Sunday, July 3, 2022

C# Interview Questions and Answers - Part 07

C# Interview Questions and Answers - Part 07

csharp-interview-questions-and-answers-part1

Are you preparing for the C# Interview? If yes, then you are at the right place. This is the C# Interview Questions and Answers article series. Here we will see the top 150+ C# Interview Questions with Answers. 

Please visit our YouTube Channel for Interviews and other videos by below link:



Please read the complete Design Patterns Interview Questions and Answers series here.


Introduction


This is the 7th part of this C# Interview Questions and Answers article series. Each part contains 10 C# Interview Questions with Answers. Please read all the C# Interview Questions list here.

I will highly recommend you to please read the previous parts over here before continuing the current part:





C# Interview Questions and Answers - Part 07


Q061. What is the difference between boxing and unboxing in C#?

The concept of boxing and unboxing underlies the C# unified view of the type system in which a value of any type can be treated as an object. Both boxing and unboxing degrade the performance, so they must be always avoided.

Boxing: 

  1. Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. 
  2. When the common language runtime (CLR) boxes a value type, it wraps the value inside a System.Object instance and stores it on the managed heap.
  3. Boxing a value type allocates an object instance on the heap and copies the value into the new object.

int number = 100;
object obj = number;

studentStruct structureObj = new studentStruct(1, 'Alex', 'alex@gmail.com');
IStudent _iStudent = structureObj;








UnBoxing:

  1. Unboxing is an explicit conversion from the type object to a value type or from an interface type to a value type that implements the interface. 
  2. Boxing is implicit but unboxing is explicit. So you have to do the required casting for unboxing. Unboxing extracts the value type from the object. 
  3. An unboxing operation consists of two steps:
  • Checking the object instance to make sure that it is a boxed value of the given value type.
  • Copying the value from the instance into the value-type variable.

int number = (int) obj;
studentStruct structureObj = (studentStruct) _iStudent;

Please watch the Boxing vs Unboxing video here and Conversion vs Casting video here for more details.



Q062. What is the difference between boxing and conversion in C#?

Both boxing and conversion are implicit conversions. The compiler does it internally.

The main difference between boxing and conversion is that, in boxing, only a value type is converted into an Object type implicitly. While in conversion a smaller value type is converted into a larger value type implicitly. 

Please watch the Boxing vs Conversion video here for more details.








Q063. What is the difference between unboxing and casting?

Both unboxing and casting are explicit conversions. The compiler cannot do it internally. So they require an explicit cast operation.

The main difference between unboxing and casting is that, in unboxing, only a reference type (object type) object is converted into a value type explicitly. While in casting a larger value type is converted into a smaller value type explicitly. 

Please watch the Unboxing vs Casting video here for more details.



Q064. What is the difference between int.Parse(),  int.TryParse() and Convert.ToInt32() methods?

In C# it is not possible to convert a string represented numbers into numeric types using conversion directly. String to integer conversion is a type conversion where an entity of string data type is changed into integer one.

So there are three inbuilt methods to do that. All the three methods int.Parse(), int.TryParse() and Convert.ToInt32() is used to convert a string representation of a number to an integer. 

Both int.Parse() and Convert.ToInt32() method throws an exception if the passed string is not a valid number whereas int.TryParse does not throw an exception if parsing fails.









int.Parse(): 

  1. The int.Parse() method returns the converted int value only if it can be converted successfully.
  2. The int.Parse() method will throw an exception if the passed string value cannot be converted into an integer safely.
  3. The int.Prase() method can throw three different types of exceptions depending on the data passed:
  • ArgumentNullException: If the parameter value is null, then it will throw an ArgumentNullException.
  • FormatException:  If the parameter value is other than integer value or not in the proper format, it will throw FormatException.
  • OverflowException: If the parameter value is out of integer ranges, then it will throw  OverflowException.

Example:

int result;
string strNum = "120";
result = int.Parse(strNum);

If you see the library code of int.Parse() method:

int-parse



int.TryParse():

  1. The int.TryParse() method returns a boolean value and accepts an out parameter which returns the converted integer value if the conversion is successful.
  2. If the string cannot be converted into int type, then the int.TryParse method returns false and zero is returned from the out parameter. But it will never throw an exception like the int.Parse() method.
  3. The TryParse method is like the Parse method, except the TryParse method does not throw an exception if the conversion fails.

Example:

int result;
string strNum = "120";
bool isSuccess = int.Parse(strNum, out result);

If you see the library code of int.TryParse() method:

int-try-parse








Convert.ToInt32():

  1. It also converts a specified string representation of a number to an equivalent 32-bit signed integer. There are multiple convert methods in C#. 
  2. If the passed value is null, it will not throw any exception like int.Parse() method but it return 0.
  3. There are different overloaded versions in the Convert class for numeric conversion.
  4. The Convert.ToInt32() method  also throws two different types of exceptions depending on the data passed:
  • FormatException:  If the parameter value is other than integer value or not in the proper format, it will throw FormatException.
  • OverflowException: If the parameter value is out of integer ranges, then it will throw  OverflowException.

Example:

int result;
string strNum = "120";
result = Convert.ToInt32(strNum);

If you see the library code for Convert.ToInt32() method:

convert-to-int

Please watch the int.Parse vs int.TryParse method video here for more details.



Q065. What is the difference between .ToString() and Convert.ToString() in C#?

Both .ToString() and  Convert.ToString() methods are used to convert an object into a string but the main difference between them is the Convert.ToString function checks and handles null values while ToString() does not. 

The ToString() method will throw a NULL reference exception if the object being converted into the string is null. On the other hand the Convert.ToString() method returns an empty string if the object is null but does not throw an exception. 

However we can check and prevent the run time NULL Reference exception in .ToString() as well by using null-coalescing operator (??) or IsNullOrEmpty() method.

The Convert.ToString() is a static method that is defined in the static Convert class under the System namespace. On the other hand, In C# the ToString() is a  virtual method defined in the  Object class in the System namespace. 

So ToString() method can be overridden based on requirement but Convert.ToString() method cannot be overridden. If you see the ToString() method:

 public virtual String ToString()
 {
     return GetType().ToString();
 }








Object.ToString is the major formatting method in the .NET Framework. It converts an object to its string representation so that it is suitable for display. Default implementations of the Object.ToString method returns the fully qualified name of the object's type.

The ToString() method has only one overloaded version which takes the IFormatProvider type. While Convert.ToString() has 36 overloaded versions which take different types of parameters. You can also pass your user-defined formatters also in Convert.ToString() method.

Convert.ToString tries to use IFormattable and IConvertible interfaces before calling base Object.ToString. The IConvertible takes precedence over IFormattable, which in turn takes precedence over Object.ToString() implementation. 

There are multiple overloaded versions for ToString() method. Please visit this link to see all the methods of the Convert class for more details.

convert-to-string

Please watch the ToString vs Convert.ToString video here.



Q066. What is the difference between String.IsNullOrEmpty() and String.IsNullOrWhiteSpace() in C#?

Both the String.IsNullOrEmpty() and String.IsNullOrWhiteSpace() are static methods which are defined in the String sealed class.

The main difference between them is that String.IsNullOrEmpty() checks whether a string is null or an empty string while String.IsNullOrWhiteSpace() checks if a string is null, empty, or an arbitrary number of spaces in the string (white space, tab, etc). 

So String.IsNullOrWhiteSpace() method covers String.IsNullOrEmpty() logic internally apart from checking the white space. Therefore in case of white space " ", tab space "\t", new line "\n" the String.IsNullOrWhiteSpace() returns true while String.IsNullOrEmpty() returns false.








If you see the library code for both methods:

is-null-or-empty

Please watch the String.IsNullOrEmpty vs String.IsNullOrWhiteSpace video here.



Q067. What is a sealed class in C#? Can you make the abstract class sealed?

In C# sealed keyword applies restrictions on the class, method, property, indexer, or event. If you create a sealed class, it cannot be extended.  In C#, we can use a sealed keyword before or after the access modifier to define the class as sealed classes.

A sealed class is used to define the inheritance depth level of a class. We can restrict a class from inheritance for security reasons in C# by declaring it a sealed class. In VB.Net "NotInheritable" keyword serves the purpose of sealing. In Java "final" keyword serves the same purpose.

A class modified by the "sealed" keyword is known as a sealed class. A sealed class is completely opposite to an abstract class since sealed classes prevent inheritance, and an abstract class is only used for extending.

Sealed classes restrict the users from inheriting the class. The sealed keyword tells the compiler that the class cannot be extended. Normally a sealed class is always the last level class in the inheritance hierarchy, but a stand-alone class can also be marked as sealed. A sealed class can also define constructors.








Fundamental Points of Sealed Class:

  1. A sealed class cannot be inherited but can be instantiated.
  2. The sealed classes can be a derived class but cannot be a base class.
  3. A sealed class cannot define any virtual member.
  4. A sealed class cannot be abstract or static.
  5. Sealed classes cannot contain any abstract methods.
  6. A sealed class can define the constructors but a constructor cannot be marked as sealed.
  7. The sealed keyword can be used either after or before the access modifier of the class.
  8.  A field variable cannot be marked as sealed.
  9. Unlike a sealed method, a non-child class can also be defined as sealed.
  10. An interface cannot be defined as sealed.

Please read the C# Sealed Class complete article here. Please also watch the C# Sealed Class video here.



Q068. What is the sealed method in C#? How can you make any method sealed?

A sealed method is used to define the overriding level of a virtual method in the inheritance. A method modified by the "sealed" keyword is known as a sealed method. A sealed keyword is used for a method to prevent it from being overridden in the derived class, i.e. to prevent the runtime polymorphic feature of OOPs.

The sealed methods in C# cannot be overridden further, but they must be used with an override keyword in the method. If you want to declare a method as sealed, then it has to be declared as virtual in its base class because a non-virtual method cannot be overridden.

A sealed method enables you to allow classes to derive from your class but prevent your specific methods from overriding by the derived class. A property can also be sealed, but you can only seal the property not the underlying setter and getter since C# offers no override syntax for setters or getters.

An interface itself cannot be declared as sealed but, it can have both virtual and sealed methods in C# 8. Please read more about the sealed interface method here.








Fundamental Points of Sealed Method:

  1. A sealed method can be only be defined in a derived or child class.
  2. The sealed keyword is always used with the override keyword.
  3. Only virtual methods of the base class can be overridden as sealed.
  4. An abstract method can also be overridden as sealed in the derived class since an abstract method is virtual implicitly.
  5. A field variable cannot be marked as sealed, because it cannot be overridden.
  6. You can specify the sealed modifier before the access modifier, before or after the override keyword.
  7. In C# 8, an interface can also define a sealed method without inheriting any base interface.
  8. A virtual interface method cannot be overridden as sealed in the derived interface.
  9. You can only prevent a sealed method from being overridden in the derived class, but it cannot prevent a sealed method from redefining it as virtual again.

Please read the complete C# Sealed Method article here. Please also watch the C# Sealed Method video here.



Q069. What is the difference between the sealed method and the private method in C#?

  1. A private method is not inherited whereas a sealed method is inherited but cannot be overridden.
  2. A private method cannot be accessed from derived classes while a sealed method can be accessed from derived classes.
  3. Only a virtual member can be sealed in the derived class, but there is no such condition for making a method private.
  4. A sealed method can only be declared in a child class while a private method can be defined in any class.
  5. The same private method can be defined in the derived class and it does not lead to an error or warning.

Please read about the C# Sealed Method vs Private Method article here








Q070. What is the difference between Sealed Class and Abstract Class in C#?

  1. An abstract class can only be used as a base class, while a sealed class cannot be used as a base class.
  2. An abstract class contains abstract methods but a sealed class cannot contain any abstract method.
  3. An abstract class contains virtual methods but a sealed class cannot contain any virtual method.
  4. An abstract class cannot be instantiated, but a sealed class can be instantiated.
  5. An abstract class cannot be the bottom-most level in the inheritance hierarchy but a sealed class may be the bottom-most.

Please read about the C# Sealed Class vs Abstract Class article here










To Be Continued Part-08...


Recommended Articles






Thanks for visiting this page. Please follow and join us on LinkedIn, Facebook, Telegram, Quora, YouTube, Twitter, Pinterest, Tumbler, and VK for regular updates.


No comments:

Post a Comment

Please do not enter any HTML. JavaScript or spam link in the comment box.