Tech Point Fundamentals

Sunday, July 31, 2022

C# Interview Questions and Answers - Part 11

C# Interview Questions and Answers - Part 11

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 11th 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 11


Q101 What is Data Annotation in C#? How can you do remote validation using it?

Data Annotations are Model Binder that is used to perform model validation within a .NET application. The advantage of using the Data Annotation validators is that they enable you to perform validation simply by adding one or more attributes to a class property.

Data Annotations Model Binder is not an official part of the Microsoft ASP.NET MVC framework. However the Data Annotations Model Binder was created by the Microsoft ASP.NET MVC team, Microsoft does not offer official product support for the Data Annotations Model Binder.

For using the Data Annotations Model Binder in an ASP.NET MVC application, you first need to add a reference to the Microsoft.Web.Mvc.DataAnnotations.dll assembly and the System.ComponentModel.DataAnnotations.dll assembly. 



The System.ComponentModel.DataAnnotations namespace has a group of classes, attributes, and methods, to make validations in our .NET applications which include the following validator attributes:

  1. Required:  Enables you to mark a property as required.
  2. StringLength:  Enables you to specify a maximum length for a string property.
  3. MaxLength: Enables you to specify the number of maximum and minimum elements in the Array property.
  4. Range: Enables you to validate whether the value of a property falls between a specified range of values.
  5. RegularExpression: Enables you to validate whether the value of a property matches a specified regular expression pattern.
  6. Compare: Enable you to compare the value of two properties
  7. DataType: Enable you to specify a type to any property like Email, PhoneNumber, Password, CreditCard, PostalCode, Html, Currency, Url, DateTime, etc.
  8. Remote: Enable you to do remote validation.

All the above attributes inherit the abstract class ValidationAttribute. ValidationAttribute validates only one Property in the object. It has an important property ErrorMessage which is used to get or set the custom validation message in case of error.



Model Validation in Entity Framework:

Since nowadays we are mostly using the Entity Framework. But if you are using the Microsoft Entity Framework to generate your data model classes then you cannot apply the validator attributes directly to your classes. Because the Entity Framework Designer generates the model classes, any changes you make to the model classes will be overwritten the next time you make any changes in the Designer.

If you want to use the validators with the classes generated by the Entity Framework then you need to create metadata classes. You apply the validators to the metadata class instead of applying the validators to the actual class. For creating a metadata class you must have to use partial class and methods. So please read the Partial Class article here and the Partial Method article here for more details.



Remote Validation: The Remote Attribute is used for remote validation. For example to check instantly whether a record already exists in the database or not.

[Remote("IsAlreadyRegistered", "Register",HttpMethod ="POST", ErrorMessage = "EmailId already exists in database.")] 
public string EmailId { get; set; } 

Here IsAlreadyRegistered is the method name that returns JSON Result, Register is the Controller Name, HttpMethod is the method request type and ErrorMessage is the user-defined message which will be displayed to the user when remote validation fails.

[HttpPost]  
public JsonResult IsAlreadyRegistered(string EmailId)  
  
return Json(IsUserAvailable(EmailId));  
}



Q102. What is Reflection? What is the use of reflection in C#?

In .Net Reflection allows you to fetch the metadata information of a Type (Assembly) at runtime or programmatically. With reflection, we can dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. 

In .Net, during the compile-time Metadata is created with MSIL and stored in a file called a Manifest. Both Metadata and Microsoft Intermediate Language together wrapped in a Portable Executable (PE) file and this can be accessed at runtime by a mechanism, called Reflection.

At runtime, the Reflection mechanism uses the Portable Executable file to read information about the assembly and it is possible to uncover the methods, properties, and events of a type, and to invoke them dynamically. 

The System.Reflection namespace and System.Type class plays a vital role in .NET Reflection. These two work together and allow you to reflect on many other aspects of a type.








GetType() Method:

The GetType() is a member of the System.Object class and the method return an instance of System.Type. Reflection generally begins with a call to a method present on every object in the .NET framework i.e GetType(). 

The main class for reflection is the System.Type class, which is an abstract class representing a type in the Common Type System (CTS). 

The Type class and its members are used to get information about a type declaration and its members such as class types, interface types, array types, value types, enumeration types, type parameters, generic type definitions, and open or closed constructed generic types, constructors, methods, fields, properties, and events of a class.

There are three way to get the type of any object i.e System.Object.GetType(), System.Type.GetType() and typeof () C# operator. 

Please watch the GetType vs TypeOf video here for more details.



System.Reflection Namespace:

The System.Reflection namespace contains classes and interfaces that provide a managed view of loaded types, methods, and fields, with the ability to dynamically create and invoke types; this process is known as Reflection in the .NET framework. 

The classes in the System.Reflection namespace, together with System.Type, enable you to obtain information about loaded assemblies and the types defined within them, such as classes, interfaces, and value types (that is, structures and enumerations). You can also use reflection to create type instances at run time and to invoke and access them. 

Reflection provides objects that encapsulate assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object. You can then invoke the type's methods or access its fields and properties. 



Reflection allows us to:

1. Use ConstructorInfo: To discover information such as the name, parameters, access modifiers (such as public or private), and implementation details (such as abstract or virtual) of a constructor. Use the GetConstructors or GetConstructor method of a Type to invoke a specific constructor.

2. Use MethodInfo:  To discover information such as the name, return type, parameters, access modifiers (such as public or private), and implementation details (such as abstract or virtual) of a method. Use the GetMethods or GetMethod method of a Type to invoke a specific method.

3. Use FieldInfo:  To discover information such as the name, access modifiers (such as public or private), and implementation details (such as static) of a field, and to get or set field values.



4. Use ParameterInfo:  To discover information such as a parameter's name, data type, whether a parameter is an input or output parameter, and the position of the parameter in a method signature.

5. Use PropertyInfo:  To discover information such as the name, data type, declaring type, reflected type, and read-only or writable status of a property, and to get or set property values.

6. Use Module: To discover information such as the assembly that contains the module and the classes in the module. You can also get all global methods or other specific, non-global methods defined on the module.

7. Use Assembly:  To define and load assemblies, load modules that are listed in the assembly manifest, locate a type from this assembly and create an instance of it.




Real Use Case of Reflection:

  • Compilers for languages such as JScript use reflection to construct symbol tables. 
  • The classes in the System.Runtime.Serialization namespace use reflection to access data and to determine which fields to persist.
  • The classes in the System.Runtime.Remoting namespace use reflection indirectly through serialization.
  • Late bindings can also be achieved through reflection. 



You can get the type using reflection as below:

int i = 42;
System.Type type = i.GetType();

You can create an instance of a class from the assembly directly using reflection:

DateTime dateTime = (DateTime)Activator.CreateInstance(typeof(DateTime));



You can use reflection to load the third-party DLL or assembly:

Assembly testAssembly = Assembly.LoadFile(@"c:\MyCustomLibrary.dll");

You can also create the instance of the type which is there in the loaded assembly:

Type calcType = testAssembly.GetType("MyCustomLibrary.Calculator");
object calcInstance = Activator.CreateInstance(calcType);

You can also access member property of the loaded assembly and create instance of them using reflection:

PropertyInfo numberPropertyInfo = calcType.GetProperty("Number");
double value = (double)numberPropertyInfo.GetValue(calcInstance, null);
numberPropertyInfo.SetValue(calcInstance, 10.0, null);



Q103. What is LINQ in C#?

  1. LINQ stands for Language Integrated Query which provides a uniform query syntax in C# and VB.NET to retrieve data from different sources and formats. 
  2. LINQ is a data querying methodology that provides querying capabilities to .NET languages with a syntax similar to a SQL query. 
  3. LINQ has great power of querying on any source of data. The data source could be collections of objects, databases or XML files.
  4. LINQ was introduced in .NET Framework 3.5 to query the data from different sources of data. 
  5. The System.LINQ namespace contains set of extension methods that allows us to query the source of data object directly in our code based on the requirement.
  6. We can easily retrieve data from any object that implements the IEnumerable<T> interface.
  7.  LINQ queries return results as objects. It enables you to use an object-oriented approach on the result set and not to worry about transforming different formats of results into objects. You will not get the result of a LINQ query until you execute it.
  8. At compile time, LINQ query expressions are converted to Standard Query Operator method calls according to the rules set forth in the C# specification. 



Types of LINQ:

There are the following LINQ Objects available in the .Net:

  1. LINQ To Objects
  2. LINQ To DataSets
  3. LINQ To SQL
  4. LINQ to XML
  5. LINQ To Entities



Advantages of LINQ:

  1. LINQ offers a common syntax for querying any type of data source. LINQ offers an object-based, language-integrated way to query over data no matter where that data came from. So through LINQ, we can query databases, XML as well as collections. 
  2. So LINQ bridges the gap and strengthens the connection between relational data and the object-oriented world
  3. LINQ has Compile time syntax checking. LINQ query expressions (unlike traditional SQL statements) are strongly typed.
  4. A LINQ query is not executed until you iterate over the query variable, hence supporting deferred execution.
  5. LINQ offers IntelliSense which means writing more accurate queries easily.
  6. LINQ offers the facility of joining several data sources in a single query as well as breaking complex problems into a set of short queries easy to debug.
  7. LINQ offers easy transformation for conversion of one data type to another like transforming SQL data to XML data.



Q104. What is Extension Method in C#? What is the difference between the Extension Method, Overloaded Method, and Overridden Method?

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type. 

Extension methods are introduced in C# 3.0 with .NET 3.5. Extension methods can be used as an approach to extending the functionality of a class in the future if the source code of the class is not available or we don’t have any permission in making changes to the class.

Before extension methods, inheritance is an approach that is used for extending the functionality of a class i.e. if we want to add any new members to an existing class without making a modification to the class, we will define a child class to that existing class and then we add new members in the child class.








Components of an Extension Method:

  1. Static Class: A static class contains all the extension methods.
  2. Static Method: A static method that defines the extension method.
  3. Binding Parameter: Type (class or interface) parameter with "this" keyword. This will always be the first parameter decorated with "this" keyword explicitly. Only one binding parameter is allowed.



public static class StringExtension
{
public static int GetWordCount(this String str)
{
if (!string.IsNullOrEmpty(str))
{
string[] strArray = str.Split(' ');
return strArray.Count();
}
else
{
return 0;
}
}

The most common extension methods are the LINQ standard query operators that add query functionality to the existing System.Collections.IEnumerable and System.Collections.Generic.IEnumerable<T> types. 

Please watch the extension method video here for a live demo.



Extension Method vs Method Overloading and Method Overriding:

You can use extension methods to extend a class or interface, but not to override them. An extension method with the same name and signature as an interface or class method will never be called. Extension methods can be overloaded as well.

At compile time, extension methods always have lower priority than instance methods defined in the type itself. So if a type has a method named Process(int i), and you have an extension method with the same signature, the compiler will always bind to the instance method. 

When the compiler encounters a method invocation, it first looks for a match in the type's instance methods. If no match is found, it will search for any extension methods that are defined for the type, and bind to the first extension method that it finds.

Please read more about method overloading here and method overriding here for more details.









Q105. What are Anonymous Types in C#? How it is different from dynamic types?

In C#, an anonymous type is a type (class) without any name that can contain public read-only properties only. Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first. The type name is generated by the compiler and is not available at the source code level. The type of each property is inferred by the compiler.

Anonymous types typically are used in the select clause of a query expression to return a subset of the properties from each object in the source sequence. LINQ queries use the anonymous types most frequently.

Anonymous types contain one or more public read-only properties. No other kinds of class members, such as methods or events, are valid. The expression that is used to initialize a property cannot be null, an anonymous function, or a pointer type.

Anonymous types are class types that derive directly from objects, and that cannot be cast to any type except object.



If two or more anonymous object initializers in an assembly specify a sequence of properties that are in the same order and that have the same names and types, the compiler treats the objects as instances of the same type. They share the same compiler-generated type information.

You cannot declare a field, a property, an event, or the return type of a method as having an anonymous type. Similarly, you cannot declare a formal parameter of a method, property, constructor, or indexer as having an anonymous type.

To pass an anonymous type or a collection that contains anonymous types, as an argument to a method, you can declare the parameter as a type object.



Typically, when you use an anonymous type to initialize a variable, you declare the variable as an implicitly typed local variable by using var. The type name cannot be specified in the variable declaration because only the compiler has access to the underlying name of the anonymous type. You create anonymous types by using the new operator together with an object initializer.

var v = new { Price = 190.00, Name = "Shirt" };

You can create an array of anonymously typed elements by combining an implicitly typed local variable and an implicitly typed array:

var array = new[] { new { name = "apple", age= 6 }, new { name = "grape", age= 8 }};



Dynamic Type:

C# 4 introduces a new type i.e. dynamic. The type is a static type, but an object of type dynamic bypasses static type checking. 

In most cases, it functions like it has a type object. At compile time, an element that is typed as dynamic is assumed to support any operation.

We can convert a dynamic object to other types very easily. This enables the developer to switch between dynamic and non-dynamic behavior.

Overload resolution occurs at run time instead of at compile time if one or more of the arguments in a method call has the type dynamic, or if the receiver of the method call is of type dynamic.



Q106. What is the difference between dynamic and var type in C#?

  1. Var type is introduced in C# 3.0 while the dynamic type is introduced in C# 4.0.
  2. For var type the variable initialization is mandatory but it is not mandatory in the case of dynamic.
  3. A var variable type is decided by the right-hand side initializer but in the case of dynamic the compiler uses Object type by default.
  4. A var type variable cannot be initialized with a null value but a dynamic variable can be initialized with a null value.


  5. The variables declared using the var keyword are statically typed while variables declared using the dynamic keyword are dynamically typed.
  6. For var, the type of the variable is decided by the compiler at compile time. But in the case of dynamic the type of the variable is decided by the compiler at run time.
  7. A var type supports IntelliSense in the visual studio because they are known at compile time but a dynamic type does not support any IntelliSense.
  8. A var type cannot be used for properties or returning values from the function but a dynamic type can be used for properties or returning values from the function.
  9. For a var type variable there will be no boxing and unboxing but in the case of dynamic type Boxing and Unboxing happen.

Please watch the boxing vs unboxing video here for more details.




Q107.  What is the difference between the “throw” and “throw ex” in .NET?

Sometimes we use a throw statement in the catch block to throw the exception to log the exception. So there are two ways to throw the exception throw and throw ex.

If we use the "throw" statement i.e throw; it preserves original error stack information. In exception handling "throw" with an empty parameter is also called re-throwing the last exception.

If we use the "throw ex" statement i.e throw(ex); the stack trace of exception will be replaced with a stack trace starting at the re-throw point. It is used to intentionally hide stack trace information.








“throw” and “throw ex”:
  1. Both are used to throw exceptions in the catch block to log messages.
  2. Both contain the same message of the exception.

“throw” vs “throw ex”:
  1. A throw is used to throw the current exception while a throw(ex) is mostly used to create a wrapper of exception.
  2. The throw(ex) will reset your stack trace so the error will appear from the line where throw(ex) is written while the throw does not reset the stack trace and you will get information about the original exception.
  3. In MSIL code when you use throw(ex) it will generate code as throw and if you use the throw it will create rethrow.

Please watch the C# Throw vs Throw ex video here








Q108. What is finally block? How many finally blocks can you define with a try block?

A finally block is an optional block that comes after a try or catches block. 

Finally block is used to execute a given set of statements, whether an exception is thrown or not thrown because a  finally block will always be executed whether an exception is raised or not. Hence it is generally used to release unmanaged resources

Only one finally block is allowed for a given try-catch block. But it is possible to define a finally block without the catch block. 

The finally block cannot contain any yield statement. Please watch the yield statement video here for more details.

Please watch the try-finally block video here for more details.



Q109. What will happen if the finally block throws an exception?

If the finally block throws an exception the original exception will be overridden and the new exception will be propagated to the higher level exceptional handler if any. 

Please watch the Try-Finally Blocks exception video here for more details. 








Q110. What is the difference between the IS and AS Operators in C#?

IS Operator:

  1. The "IS" operator is used to check whether the run-time type of an object is what we expect it to be. 
  2. It is a binary operator that returns a Boolean indicating whether or not the instance is in fact of the type specified as the second operand. 
  3. In C# 6 and earlier, the IS operator checks if the result of an expression are compatible with a given type. 
  4. But beginning with C# 7.0, you can also use the IS operator to match an expression against a pattern. 
  5. Beginning with C# 9.0, you can use a negation pattern to do a non-null check.
  6. The IS operator takes into account boxing and unboxing conversions implicitly.








AS Operator:

  1. The "as" is C#’s true safe casting operator.
  2. The "as" operator is used to perform conversions between compatible types. 
  3. In case of compatibility, it will return the value of the new object type otherwise, null will be returned.
  4. If the conversion from one type to another type fails, then it will return a null value instead of raising an exception. So, the return value can be null also.
  5. We cannot perform conversion of value types (int, double, char, bool) and user-defined types. Because the return type should be the reference or nullable type for the AS operator.

Please watch the IS vs. AS video here for more details. 


To Be Continued Part-12...


Recommended Articles






Thanks for visiting this page. Please follow and join us on LinkedInFacebookTelegramQuoraYouTubeTwitterPinterestTumbler, and VK for regular updates.

No comments:

Post a Comment

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