Tech Point Fundamentals

Sunday, June 19, 2022

C# Interview Questions and Answers - Part 05

C# Interview Questions and Answers - Part 05

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 5th 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 to please read the previous parts over here before continuing the current part:





C# Interview Questions and Answers - Part 05


Q041. What is the difference between static class and singleton?

Singleton is a design pattern that makes sure that the application creates only a single instance of the class at any time. A static method is used for singleton implementation. 

On the other hand for a static class, a single instance remains in memory for the lifetime of the Application Domain in which your program resides and it is accessed globally throughout the application. 








Below are some main differences between static class and singleton:

  1. Singleton is a pattern not a keyword like static. So for creating a static class static keyword is sufficient while in the case of singleton there is a need to write the logic for the singleton.
  2. Singleton class must have a private default instance constructor while a static class cannot contain any instance constructor.
  3. A static class is neither instantiated nor extended while a singleton class can be.
  4. A static class is sealed implicitly but the singleton class must be decorated as sealed explicitly.
  5. It is possible for a singleton to implement the interface or inherit from another class but the static class neither implements the interface nor extends from any other class.
  6. We cannot implement the dependency injection with a static class but DI is possible with the singleton class because it can be interface driven.
  7. The scope of the static class is at the app domain level because it is managed by the CLR while the scope of the singleton object is across the application lifecycle.
  8. A static class cannot have any destructor but a singleton class can define a destructor.
  9. The singleton class instance can be passed as a parameter to another method while a static class cannot be because it contains only static members.

Please read the complete singleton pattern article here and the static class article here for more details.



Q042. What is the use of static class? Can you give me some real examples of static classes and static methods available in the .Net?

Static classes are used to define methods and properties which are global for all the applications.

  1. Static classes and methods are used for creating Extension Methods.
  2. The main advantage of a static class is that it guarantees that only one global instance will be created by the CLR and no instantiation is allowed.
  3. A static class can be used to implement helper or utility classes as static classes don’t need to be instantiated or inherited and generally contain a collection of some reusable methods and properties.



Below are some real examples of static class and static methods available in the .Net Framework:

  • System.Math is a static class  
  • System.IO.File is a static class
  • System.Environment is static class class
  • System.String is a sealed class that contains static methods (like Format, Compare, Concat, Equals, Join )
  • System.TimeZone is an abstract class that contains CurrentTimeZone and IsDaylightSavingTime static method
  • System.DateTime is a structure that contains a lot of static methods and operators (like Now, UtcNow, Today, Parse, Equals)
  • System.Int16, System.Int32 and System.Int64 are structures that contain Parse, TryParse static methods
  • System.Double and System.Single are structures that contains a lot of static methods and operators (like Parse, TryParse, IsInfinity, IsNaN, IsNegativeInfinity, IsPositiveInfinity, operator ==, !=, <,>,<=,>=)
  • System.Boolean is a structure that contains Parse and TryParse static methods

Please read the C# Static Class article here and the Static Class video here.








Q043. What is a partial class in C#? What is the use of partial class, do you have any real examples?

In C#, we can split the implementation of a class, interface, or struct in multiple files using the partial keyword.  The partial keyword is used to create partial types. 

The partial keyword indicates that other parts of the class, interface, struct, or method can be defined anywhere in the namespace.   So partial class, partial interface, and the partial structure were introduced in C# 2.0.

When we define your class, interface, or struct with the partial keyword, you or someone else is allowed to extend the functionality of your class with another class, which also needs to be declared as partial. 







All the parts must use the partial keyword and must be available at compile time to form the final type.  The compiler combines all the implementation from multiple .cs files when the program is compiled.

A class declared with a partial keyword is called a partial class. A partial class is a special feature of C# which provides the ability to implement the functionality of a single class into multiple code files. 

All these files are combined into a single class file when the application is compiled, so all the parts must be available at compile time.



The fundamental point about the partial class is as follows:

  1. The partial modifier must be used just before the class keyword name.
  2. All the parts must be declared with a partial keyword, otherwise, it causes a compile-time error.
  3. Every part must be defined in the same namespace (Assembly, DLL, or EXE).
  4. Each part must be available at compile time to form the final type.
  5. You can also have a constructor and destructor in a partial class.
  6. A partial class can have partial methods.
  7. All the parts must have the same accessibility (public, private, protected, etc).
  8. If any part is declared as abstract, then all the part is considered abstract. 


  9. If any part is declared as sealed, then all the part is considered sealed.
  10. Inheritance between the partial parts is not allowed.
  11. The class member declared in a partial definition will be available to all the other parts.
  12. If any part declares a base type, then all the other parts also inherit that class automatically. 
  13. All the parts can specify different base interfaces, but the final type implements all the interfaces listed by all the partial declarations.
  14. Nested partial types are allowed.
  15. All the parts can specify different class attributes (like SerializableAttribute, ObsoleteAttribute), but all the attributes are merged at compile time.
  16. At compile time XML-Comments of different parts will be merged.

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



Q044. What is a partial method in C#? What is the use of partial methods?

A method defined with the keyword partial is known as a partial method in C#. A partial method can be split into two separate code files of partial types.  

A partial method declaration consists of two parts: the definition and the implementation. Usually, a partial method has its signature defined in one part of a partial type, and its implementation may be defined in another part of the partial type.  But it is valid to have both in the same part of the partial type. 

One of the partial type files (.cs file) must contain a signature of the method, and other files can contain the optional implementation of the partial method. But both declaration and implementation of a method must have the partial keyword.






It is mandatory to have the signature of the partial method, but it is not mandatory to provide the implementation. A partial method gets executed only when it has an implementation. If the method is not implemented, then the compiler removes the method signature and all calls to the method.

There will be no compile-time or run-time errors if the partial method is called but not implemented. If the implementation is not supplied, then the method and all calls to the method are removed at compile time by the compiler itself.

The partial method was introduced in C# 3.0 with the .Net Framework 3.0.  Until C# 7, partial methods are not allowed in the partial interface but in C# 8, you can define partial methods in the partial interface as well. Please read more about the partial interface method here.



Below are some fundamental points of partial methods:

  1. A partial method can only be created in partial types (partial class, partial struct, or partial interface).
  2. The return type of a partial method must be void.
  3. You cannot specify any access modifiers explicitly even private to a partial method, they are private implicitly by default.
  4. Both declaration and implementation of a partial method must use the partial keyword.
  5. Method signatures in both parts of the partial type must match.
  6. You cannot provide the definition along with the implementation for a partial method. Both definition and implementation of a partial method must be in separate partial type files or in the same partial type but separately.
  7. The partial method cannot have multiple declaration definitions.
  8. Although the partial method's implementation definition is optional, you cannot have multiple implementation definitions for a partial method.
  9. A partial method can have IN and REF type parameters but not OUT parameters. Out parameters are like return values that must be assigned by the callee, and we know that a partial method has optional implantation in the case if it does not have any implementation how will it assign value to the out parameters.  


  10. All the partial methods are implicitly private, so cannot be virtual.
  11. A partial method cannot be extern, because the presence of the body determines whether they are defining or implementing.
  12. A partial method cannot be abstract or sealed.
  13. A partial method can be static or unsafe.
  14. You can create a delegate to a partial method that has been declared and implemented, but not to a partial method that has only been declared.
  15. You can also have partial generic methods.
  16. Method overloading is allowed for partial methods.
  17. You can also declare and define partial events as well.
  18. You cannot override the base class abstract method as partial.

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



Q045. Can you give me some real examples or use of partial classes and partial methods available in the .Net?

The visual studio uses partial classes to separate automatically generated code from the developer's code. With the help of partial classes, you can split the UI of the design code and the business logic code to read and understand the code. 

When you were working with automatically generated code, the code can be added to the class without having to recreate the source file like in the visual studio. 

Following are the real examples of partial classes in .Net:

1. Web Form Application: In the Web Form Applications, the visual studio uses partial classes for creating aspx files.  Each aspx file contains two files with partial classes; one is "aspx.cs" and other is "aspx.designer.cs". 

2. Window Form Application: In the Windows Form Applications, the visual studio uses partial classes for creating windows forms. Each windows form contains a ".Designer.cs" with a partial class. 

3. ADO.Net Entity Data Model: When you add any ADO.Net Entity Data Model, along with the ".edmx" file visual studio creates different partial classes in the different source files.



4. LINQ To SQL Class: In LINQ to SQL Classes, when you add any database object into ORD (Object Relational Designer), the visual studio creates a ".designer.cs" also along with the ".dbml" file which contains partial classes. For each object of ORD (like database tables, stored procedures, functions) there is a corresponding partial class into the ".designer.cs" file. This file also contains a lot of partial methods related to the database as well. 

5. Data Set Designer(XSD File): When you add any Dataset Designer file (.xsd file) in the project, the visual studio creates a ".Designer.cs" file along with the ".xsd" file which contains auto-generated partial classes. Also for each item of the designer, there is a corresponding partial class in this ".Designer.cs" file. 

6. WPF User Controls: When you add any WPF user controls, along with the ".xaml" file, the visual studio also creates an auto-generated code-behind file ".xaml.cs" with partial classes. 

7. Model Validation in Entity Framework: If you want to add data annotation model validations in the Entity Framework, you must have to define the metadata class which should be a partial class only.

Please read the C# Partial Class Real Examples article here. Please also watch the C# Partial Class Real Examples video here.








Q046. What is the difference between int and Int32 in C#? 

Int32 and int are synonymous in C#, both of them allow us to create a 32-bit integer. The int is basically a shorthand notation (alias) for Int32. 

Whether we use int or Int32 to create an integer, the behavior is identical. The only place where Int32 is not allowed is when creating an enum.

To use Int32, either we need to use using System declaration or specify the fully qualified name (System.Int32) whereas with int it is not required.



Q047. What is the difference between string and String? or What is the difference between string keyword and System.String class in C#?

C# has two different ways to refer many of its fundamental types i.e. String or string, Boolean or bool, Int32 or int, etc.

In fact, the string is not even a type. It is just an alias for System.String which is a sealed class basically. Whenever you use the string it is equivalent to type System.String. The same thing goes for all the other alias types as well.

In C# string keyword is an alias for System.String class. Therefore System.String and string keywords are the same, and we can use whichever naming convention we prefer. 



The String class provides many methods for safely creating, manipulating, and comparing strings. But whenever you use String, you have to provide the System namespace.

You can define another class with the name String inside any namespace also. But if you have defined any variable with String type it will cause an error as the compiler found a class with the name String in the current namespace. The aliased type (string, int, bool) prevents C# from getting confused with user-defined types with the same name.

Please watch the string vs String video here.








Q048. What is the difference between String and StringBuilder in C#?

  1. In C#, the string type is immutable (read-only) i.e. a string cannot be changed once it is created, it always creates a new object of string type in memory. On the other hand, StringBuilder is used to represent a mutable string of characters i.e the StringBuilder does not create a new object in the memory on string modification.
  2. StringBuilder is faster than string when appending multiple string values because it does not create a new object in the memory.
  3. StringBuilder is available in System.Text namespace while String is available in System namespace.
  4. The StringBuilder is not the same as the string, so the ToString() method is used to retrieve the string value from the StringBuilder object.StringBuilder is normally used when there is a need for frequent modification of string.
  5. Due to immutable behavior, the string is thread-safe so they can be used across threads without fearing synchronization problems while the StringBuilder object is not thread-safe. 
  6. A StringBuilder object maintains a buffer to accommodate expansions to the string while String does not.

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








Q049. What do you understand by the term 'TypeSafe'? Is C# a typesafe language?

Type safety in .NET has been introduced to prevent the objects of one type from peeking into the memory assigned for the other object. Writing safe code also means preventing data loss during the conversion of one type to another. 

In C# most of the non-generic collections like ArrayList, HashTable, etc are non-typesafe because they work on Object type internally. Boxing and Unboxing are involved in the non-generic collections.

C# is a TypeSafe, Strongly-Typed, Managed, and Object-Oriented language which is compiled by the .Net Framework (cs compiler) for generating the MSIL code. 

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



Q050. What are Tuples in C#? What is its main use of it?

C# tuple is a data structure that is used to store a sequence of elements. A tuple with n elements is known as n-tuple. In C#, a tuple is a class that contains static methods. These methods are used to create tuple objects.

Tuple<int, string, string> user = new Tuple <int, string, string>(1, "Tech Point", "admin");

The Tuple<T> class was introduced in .NET Framework 4.0. A tuple is a data structure that contains a sequence of elements of different data types.

In the .NET Framework 4.7 with C# 7.0, Microsoft has introduced the ValueTuple structure, which is a value type representation of the Tuple. It is available in the System namespace.



A Tuple was a reference type and not a value type. So it was allocated on the heap and could result in CPU-intensive operations. But Tuples in C# 7 are values, so they are copied by value, rather than by reference.

The Tuple is limited to include eight elements. You need to use nested tuples if you need to store more elements. 

The Tuple elements can be accessed using properties with a name pattern Item<elementNumber>, which does not make sense.

Use of Tuples:
  • A method can have a tuple as a parameter. So when you want to pass multiple values to a method through a single parameter.
  • A Tuple can be returned from a method. So when you want to return multiple values from a method without using ref or out parameters.
  • When you want to hold a database record or some values temporarily without creating a separate class, you can use tuples.


To Be Continued Part-06...


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.