Tech Point Fundamentals

Sunday, June 26, 2022

C# Interview Questions and Answers - Part 06

C# Interview Questions and Answers - Part 06

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 6th 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 06


Q051. What is the difference between value type and reference type?

In C#, the data types are categorized based on how they store their value in the memory. Considering this there are the following three types basically i.e value type, reference type, and pointer types.

A. Value Types:

  1. A variable of a value type contains an instance of the type. This differs from a variable of a reference type, which contains a reference to an instance of the type.
  2. All the value types are derived from System.ValueType and System.ValueType is derived from the ultimate super base class System.Object
  3. A value type data type holds a data value within its own memory space i.e value type variables contain directly values.


  4. A value type can be either an enum type or a structure type. All the primitive types are value types that are basically derived from an enum. For example - bool, int, char, enum, double, structure, etc.
  5. All the value types are stored in the stack. So a Value Type stores its contents in memory allocated on the stack.
  6. By default, on assignment, passing an argument to a method, and returning a method result, variable values are copied.
  7. Any operation on a value-type variable affects only that instance of the value type, stored in the variable.
  8. If a value type contains a data member of a reference type, only the reference to the instance of the reference type is copied when a value-type instance is copied. Both the copy and original value-type instance have access to the same reference-type instance.
  9. A value type variable cannot be null because it holds value, not a memory address. C# 2.0 introduced nullable types, using which you can assign null to a value type variable or declare a value type variable without assigning a value to it.
  10. A nullable value type T? represents all values of its underlying value type T and an additional null value. You cannot assign null to a variable of a value type unless it's a nullable value type.



B. Reference Types:

  1. On the other hand, Reference Types are used by a reference that holds a reference (address) to the object but not the object itself. 
  2. So a reference type doesn't store its value directly. Instead, it stores the address where the value is being stored.
  3. Since reference types represent the address of the variable rather than the data itself, assigning a reference variable to another doesn't copy the data.
  4. All the non-primitive data types are reference types. For example - string, class, delegate, array, and interface.
  5. The default value of a reference type variable is null when they are not initialized. Null means not referring to any object.
  6. All the reference types values are stored in the heap, but the variable is stored in the stack which points to the memory address of the referenced object. So when a reference type variable is no longer used, it can be marked for garbage collection.



C. Pointer Types:

  1. Generally, most of the C# code we write is "verifiably safe code", which means .NET tools can verify that the code is safe. 
  2. A safe code doesn't directly access memory using pointers. Instead, it creates managed objects directly. But C# also supports an unsafe context by pointers.
  3. A C# pointer is nothing but a variable that holds the memory address of another type. 
  4. But in C# pointer can only be declared to hold the memory address of value types and arrays. 
  5. Unlike reference types, pointer types are not tracked by the default garbage collection mechanism. That's why pointers are not allowed to point to a reference type or even to a structure type that contains a reference type. 
  6. So pointers can point to only unmanaged types which include all basic data types, enum types, other pointer types, and structs that contain only unmanaged types.



Q052. What is the difference between reference type and pass-by-reference?

Reference Types are the data types that hold a reference (address) to the object. They are stored in the heap. 

Since reference types represent the address of the variable rather than the data itself, assigning a reference variable to another doesn't copy the data. On the other hand, pass-by-reference is a way to pass a value type object or variable as a reference to a method as a parameter.

When you pass a reference type variable from one method to another, it doesn't create a new copy; instead, it passes the variable's address. So, if we change the value of a variable in a method, it will also be reflected in the calling method.

In c#, passing a value type parameter to a method by reference means passing a reference of the variable to the method. So the changes made to the parameter inside the called method will affect the original data stored in the argument variable.



We use OUT and REF keywords to pass a value type as a reference type in C#. Don't confuse the concept of passing by reference with the concept of reference types. The two concepts are not the same.

A method parameter can be modified by ref regardless of whether it is a value type or a reference type. There is no boxing of a value type when it is passed by reference. 
If you pass a reference type object (class object) as a parameter, it sends the address, not the actual data which is referenced by the reference type object.

Please watch the Reference Type vs Pass By Reference video here.

Now anyone can get confused about string because it does not follow the above rule. Actually, a string is a reference type, but it is immutable. It means once we assigned a value, it cannot be changed. 

If we change a string value, then the compiler creates a new string object in the memory and points that variable to the new memory location. So, passing a string value to a function will create a new variable in the memory, and any change in the value in the function will not be reflected in the original value. 

Please watch the String vs StringBuilder video here for more details.




Q053. What is the difference between OUT and REF type parameters?

In C# both REF and OUT are known as reference parameters that are used for passing an argument by reference. Properties are not variables, therefore it cannot be passed as an out or ref parameter.

Both REF and OUT are treated differently at run time but they are treated the same at compile time. So two methods cannot be overloaded if one method takes an argument as REF and the other takes an argument as an OUT. 






REF Parameter:

  1. A method parameter can be modified by REF regardless of whether it is a value type or a reference type. There is no boxing of a value type when it is passed by reference.
  2. An argument that is passed to a REF parameter must be initialized before it is passed.
  3. To use a REF parameter, both the method definition and the calling method must explicitly use the REF keyword.
  4. REF is used to state that the parameter passed may be modified by the method. So the REF parameter may or may not be modified by the called method.



OUT Parameter:

  1. Variables passed as OUT arguments do not have to be initialized before being passed in a method call. 
  2. The OUT is used to state that the parameter passed must be modified by the called method. So the called method is required to assign a value before the method returns.
  3. To use an OUT parameter, both the method definition and the calling method must explicitly use the OUT keyword. 
  4. The OUT keyword can also be used with a generic type parameter to specify that the type parameter is covariant.

Please read the method overloading rules for REF vs OUT here for more details. 



REF vs OUT Parameter:

Following are the most common difference between REF vs OUT:

  1. The REF parameter must be initialized before it is passed to the ref parameter. But it is not mandatory for the OUT parameter.
  2. In the called method, it is mandatory to initialize the OUT parameters before using or returning to the calling method. But it is not mandatory for REF parameters.
  3. A REF type parameter is bi-directional i.e it can be used to pass a value and get the updated value from the called method. But OUT parameter is uni-directional i.e it can only be used to get the value from the called method.

Please watch the OUT vs REF video here.




Q054. Can you pass a constant as a reference? Why?

No, a constant variable can not be passed as a reference in C#. There are below justification for that:

Constants are something that is used for holding a value that can not be changed during the program or app domain.

Constants are compile-time constants, so they must be set along with the declaration itself.
By default, all the const types are static internally.

Please watch the Const vs Readonly video here.









Q055. If a method's return type is void, can you use a return statement in the method? What is the use of the return keyword?

Yes, we can use the return keyword but without any value. 

A void function performs a task, and then control returns back to the caller but it does not return a value. 

You can use the return statement, as there is no return value. Even without the return statement, control will return to the caller automatically at the end of the function.




Q056. What is a recursive method? Can you tell me any available recursive method names in C#?

In C# there is no difference between function and method except that functions are not utilizable outside of their classes usually because they are declared as private. In C# we had only methods but the anonymous function has been added to C#, since .NET Framework 3.5.

A recursive function is a function that calls itself. A function that calls another function is normal and used in daily programming but when a function calls itself then it is a recursive function.

A recursive algorithm is a special type of algorithm in which a method calls itself over and over again to solve a problem. Each successive call reduces the complexity of the problem and moves closer and closer to a solution until finally a solution is reached, the recursion stops, and the method can exit.  

Recursive algorithms are fairly easy to identify because the method name appears in the method body. Recursive algorithms are about breaking complex problems down into smaller more manageable problems.

Real Examples of Recursion:

  1. Binary Search
  2. Tower of Hanoi Problem
  3. Fibonacci Numbers
  4. Factorial Numbers
  5. Merge Sort
  6. Directory and file Search



Q057. In C# strings are the value type or reference type? How?

In C# strings are reference types but behave like value types.  Actually, a string is a reference type, but it is immutable. It means once we assigned a value, it cannot be changed. 

If we change a string value, then the compiler creates a new string object in the memory and points that variable to the new memory location. 






So, passing a string value to a function will create a new variable in the memory, and any change in the value in the function will not be reflected in the original value. 

Please watch the String vs StringBuilder video here for more details.




Q058. Enums are value type or a reference type in C#? 

In C# enums are value type. An enumeration type is a value type defined by a set of named constants of the underlying integral numeric type. By default, the associated constant values of enum members are of type int; they start with zero and increase by one following the definition text order. 

The System.Enum type is the abstract base class of all enumeration types in C#. It provides a number of methods to get information about an enumeration type and its values

You cannot define a method inside the definition of an enumeration type. To add functionality to an enumeration type, create an extension method.



Q059. In C#, the structure is a value type or a reference type?

Structures are value types in C#. A structure or struct is a simple user-defined type and lightweight alternative to a class.  A struct is simply a composite data type consisting of any number of other types. 

In C# all struct types are implicitly inherited from System.ValueType which, in turn, inherits from the System.Object class, so, it is possible to override the methods of the Object class inside a struct by using the keyword override. Remember that this is a special case in C# structs. 



Structure Fundamental Points:

  1. In C# structs are value types. The default modifier is internal for the struct and its members.
  2. A structure can contain only a parameterized constructor or a static constructor.
  3. Like a class, a structure can also contain constants, fields, methods, properties, indexers, operators, events, and nested types. A struct can also contain static members, but a static member of the struct type is referenced.
  4. A struct can also be passed by reference to a method using a REF or OUT parameter. Boxing and Unboxing are used internally to convert between a struct type and object.
  5. A struct does not support inheritance, but it can implement interfaces. So a struct cannot inherit from any struct or class.


  6. The accessibility of a struct member cannot be protected or protected internal because inheritance is not supported for structs.
  7. A struct member cannot be specified as abstract, sealed, virtual. But a struct can be partial.
  8. A struct cannot contain any explicit default constructor i.e parameterless constructor because every struct implicitly has a parameterless instance constructor that always sets the default value to its member fields.
  9. Parameterized constructors are allowed but destructors or finalizers are not allowed in any structure.
  10. A structure can never be abstract because all the structures are implicitly sealed. So abstract and sealed modifiers are not allowed in a struct declaration.
  11. Instance field member declarations for a struct are not permitted to include variable initializers. But static fields of a struct are permitted to include variable initializers.
  12. It is not possible for the value of a struct type to be null because structs are not referenced types.

Please read the complete C# Structure article here




Q060. What is the difference between casting and conversion in C#?

Since C# is statically-typed at compile-time, after a variable is declared, it cannot be declared again or assigned a value of another type unless that type is implicitly convertible to the variable's type. 

However, you might sometimes need to copy a value into a variable or method parameter of another type. To achieve that there are two different ways in C# i.e Casting and Conversion.

The main difference between type conversion and typecasting is that type conversion is done “automatically” by the compiler whereas, typecasting is done “explicitly" by the programmer.






1. Conversion: An implicit conversion in C# is known as conversion. The compiler does it internally. No special syntax is required because the conversion always succeeds and no data will be lost. The conversion includes conversions from smaller to larger integral types, and conversions from derived classes to base classes.



2. Casting: An explicit conversion in C# is known as casting. This explicit conversion requires a cast expression known as cast operator. Casting is required when information might be lost in the conversion, or when the conversion might not succeed for other reasons. For example numeric conversion to a type that has less precision or a smaller range, and conversion of a base-class instance to a derived class.

Apart from this, there are some inbuilt helper classes as well in the .Net framework for doing the explicit conversion for example System.Convert class and Int32.Parse etc. Please watch the Conversion vs Casting video here.

Boxing and Unboxing are not the same as conversion and casting. Please watch the boxing vs unboxing video here for more details.









To Be Continued Part-07...


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.