C# Questions
https://www.toptal.com/dot-net/interview-questions
What is Object oriented Programming?
It is a programming methodology in which the programs are organized as collections of objects. Each object represents an instance of some class. The classes can be interrelated to each other through inheritance. Abstraction, Encapsulation, Inheritance and Polymorphism are the core OOP’s concepts:
What is a Class?
A template for a set of objects that share a common structure and a common behavior.
What is an Object?
An instance of a class. It has state, behavior and identity.
What is Inheritance?
Inheritance is a relationship among classes, wherein one class shares the structure or behavior defined in another class. This is called Single Inheritance. If a class shares the structure or behavior from multiple classes, then it is called Multiple Inheritance. Inheritance defines “is-a” hierarchy among classes in which one subclass inherits from one or more generalized superclasses.
What is Abstraction?
allows us to define a common definition of a base class. Abstraction defines the essential characteristics of an object that distinguish it from all other kinds of objects. Abstraction provides crisply-defined conceptual boundaries relative to the perspective of the viewer. Its the process of focusing on the essential characteristics of an object. Abstraction is one of the fundamental elements of the object model.
What is Polymorphism?
literally means taking more than one form. Polymorphism is a characteristic of being able to assign a different behavior or value in a subclass, to something that was declared in a parent class. Provides us with extensible methods . We can have different methods with same name, but with different kinds of behavior. There are two types of Polymorphism.
Compile time: function or operator overloading
Runtime: Inheritance & virtual functions that multiple derived classes can share.
What is Encapsulation?
The process of compartmentalizing the elements of an abstraction that defines the structure and behavior. Encapsulation helps to separate the contractual interface of an abstraction and implementation.
Advantages Of Encapsulation:
- -A. Code re-usability: define a class and n number of objects implement the class
- -B. Inheritance: Eliminates redundant code and extend the use of existing classes.
- -C. Encapsulation: The programmer can hide the data and functions in a class from other classes. It is accomplished through modifiers like private, protected, and protected internal.
- -D. Easy to Maintain and Upgrade: If we want to make changes in a class, we can make them and save the changes in the .dll This .dll can easily be updated in the client by using Update Reference.
- -ABOVE is C# Tutorial : Sample code -> http://www.csharp-station.com/Tutorial/CSharp/SmartConsoleSetup.aspx
How can we achieve multiple inheritance in C#?
In C# Multiple Inheritance can be affected using Interface. We can implement multiple interfaces. But we cannot inherit multiple Base Classes. Here multiple interfaces can be used using comma(,). Thus allowing multiple inheritance, by implementing more than interface.
What is an Interface?
Interface is an outside view of a class or object which emphasizes its abstraction while hiding its structure and secrets of its behavior.
How do we use Interface Variables?
https://stackoverflow.com/questions/2151959/using-interface-variables
https://orcharddojo.net/orchard-resources/Library/DevelopmentGuidelines/BestPractices/CSharp
What is Base Class?
https://stackoverflow.com/questions/10503255/what-does-the-base-syntax-mean
What are Extension Methods?
public static int Foo(this MyClass arg)
Methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method.
What is an Abstract class?
Abstract class is a class that has no instances. An abstract class is written with the expectation that its concrete subclasses will add to its structure and behavior, typically by implementing its abstract operations. We can also have an abstract class without any abstract methods. DEFINITION—>
http://aspnettutorialonline.blogspot.com/2012/03/abstract-classes-definition-with.html
What are Delegates?
Delegates are objects used to call the methods of other objects. Delegates allow methods to be passed as parameters.
Delegates can be used to define callback methods.
Delegates can be chained together; for example, multiple methods can be called on a single event. Whenever a Normal C# method is called each time the memory is allocated for that Method. But When a Delegate is called Memory will not be created each time it is called. Memory is allocated only once for the Delegate. We can treat delegate as a Global Method and be called throughout the Application.
Advantages
- Encapsulating the method’s call from caller
- Effective use of delegate improves the performance of application
- Used to call a method asynchronously
- Declaration
How to create and use delegates? Scenario you used delegate.
-public delegate void ProcessBookDelegate(Book book);
-An eventing design pattern is used.
-It is desirable to encapsulate a static method.
-The caller has no need to access other properties, methods, or interfaces on the object implementing the method.
-Easy composition is desired.
-A class may need more than one implementation of the method.
-Events or notifications, changes in components to listeners
What are Access modifiers?
Access modifiers allow you to define or restrict access to certain features. Access modifiers are an integral part of object-oriented programming. They support the concept of encapsulation, which promotes the idea of hiding functionality.
In C# there are 5 different types of Access Modifiers.
Public – There are no restrictions on accessing public members.
Private – Access is limited to within the class definition. This is the default access modifier type if none is formally specified
Protected – Access is limited to within the class definition and any class that inherits from the class
Internal – Access is limited exclusively to classes defined within the current project assembly
Protected internal – Access is limited to the current assembly and types derived from the containing class. All members in current project and all members in derived class can access the variables.
Can you prevent a class from overriding?
The default access modifier for a class is internal if it’s defined within the same namespace. It is private if it’s defined within another class.
Yes, use sealed modifier on a method
How do you override a method?
Use the (virtual, abstract, or override) word on the method
What is sealed? When to use it/Advantages of those?
Sealed is a keyword that prevents any class from inheriting from the sealed class.
Difference and similarities between Class and Struct?
Structs are value types and classes are reference types.
https://stackoverflow.com/questions/13049/whats-the-difference-between-struct-and-class-in-net
16) What is an Abstract method? When to use it/Advantages of those?
Abstract methods, similar to methods within an interface, are declared without any implementation. They are declared with the purpose of having the child class provide implementation. They must be declared within an abstract class.
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/abstract
17) What is Method overloading? When to use it/Advantages of those?
Writing a method that excepts various parameters. Different amounts of parameters and data types of the perimeters.
18) What is Method Overriding? When to use it/Advantages of those?
Writing a new Method for an inherited Method.
19) What is a Virtual Method? When to use it/Advantages of those?
A Keyword used to modify a method, used in place of static, abstract, private. You cannot override a non-virtual method. Loaded during run-time. To modify a method or override.
20) What is a Static field and Static Method? When to use it/Advantages of those?
A static field is one which is loaded at start. A static Method is loaded at start time.
21) What is Data encapsulation? When to use it/Advantages of those?
A term used to describe Hiding of code or abstract classes. Code re-usability, Secrecy.
23) What are reference types and value types? When to use it/Advantages of those?
Reference is a pointer to a value like object. Value is directly stored value like Struct. Struct objects load faster.
https://www.infoq.com/news/2018/07/structs-performance-csharp
25) What is a property? When to use it/Advantages of those?
A way to simplify syntax. Get{}set{}
26) What is Dispose for? When to use it/Advantages of those?
Dispose is a method of elimination. To eliminate a connection to a database. To free up memory
27) When do we use finally block? What is Finalize()? What it is for?
The finally block always executes when the try block exits, except System.exit(0) call. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.
Finalize() method helps in garbage collection. A method that is invoked before an object is discarded by the garbage collector, allowing it to clean up its state. Should not be used to release non-memory resources like file handles, sockets, database connections etc because Java has only a finite number of these resources and you do not know when the garbage collection is going to kick in to release these non-memory resources through the finalize() method.
28) What is Enum?
Keyword to declare Enumeration or create a strict list. When to use it/Advantages of those? To prevent an invalid parameter.
29) What is Early binding vs late binding? When to use it/Advantages of those?
30) Early Binding is loaded at compile time. Late binding are targets at runtime.
Early is Non-virtual methods, late is Virtual methods.
31) Why is it preferred to not use finalize for clean up?
It uses up resources and its more code.
32) How can we suppress a finalize method?
- SuppressFinalize ()
33) How do I force the Dispose method to be called? Call the dispose() method.
34) In what instances you will declare a constructor to be private?
If you do not want a class to be instantiated. A default constructor can not be set. To prevent creating instances of a class when there are no instance fields.
35) What is the difference between System.String and System.StringBuilder classes?
Immutable- string creates and destroys instances to change string. Mutable – StringBuilder is a buffer of characters that can be changed. Best use cases: https://stackoverflow.com/questions/21644658/how-to-use-stringbuilder-wisely
36) Can we have different access modifiers on get/set methods of a property?
- Yes, on properties
- No, we cannot have different modifiers same property. The access modifier on a property applies to both its get and set accessors.
39) What are Constructors?
A constructor is a method in the class which gets executed when its object is created. Usually, we put the initialization code in the constructor. If no constructor defined then the CLR will provide an implicit constructor which is called as Default Constructor. A class can have any number of constructors provided they vary with the number of arguments that are passed, which is they should have different signatures. Constructors do not return a value Constructors can be overloaded
public class mySampleClass
{
public mySampleClass()
{
// This is the no parameter constructor method.
// First Constructor
}
public mySampleClass(int Age)
{
// This is the constructor with one parameter.
// Second Constructor
}
public mySampleClass(int Age, string Name)
{
// This is the constructor with two parameters.
// Third Constructor
}
// rest of the class members goes here.
}
40) What is the singleton design pattern?
The basic purpose it is simple: the class can only has one instance at a time. class
The implementation does two things:
- sets the constructor to private thereby nowhere else outside of the class can instantiate the class.
- exposes an instance of itself by a public static property; if the instance does not exist yet, instantiates one.
41) What is an Indexer?
http://aspnettutorialonline.blogspot.com/2012/03/indexers-definition-with-example-in.html
Similar to indexing a table field.
41) What is Boxing and Unboxing?
Boxing – Converting a value type to reference type is called boxing. Boxing happens implicitly. An example is shown below.
int i = 101;
object obj = (object)i; // Boxing
Unboxing – Converting a reference type to a value type is called unboxing. Unboxing is an explicit conversion. An example is shown below.
obj = 101;
i = (int)obj; // Unboxing
Boxing a value type allocates an object instance on the heap and copies the value into the new object. Due to this boxing and unboxing can have performance impact.
42) What are Generics? Advantages of that?
Generic help us to create flexible strong type collection.
Generics result in better performance because you can avoid boxing/unboxing. Generic basically separate the logic from the datatype in order maintain. better reusability, better maintainability etc.
43) How do you declare Generic Methods?
Generic method is defined by specifying the type parameter after the method name but before the parameter list.
Doe Example public string Add<T>(T val1, T val2).
44) Difference between Generics and Array List?
- Array List is not type safe because it faces problems of boxing and UN boxing.
- List generics are type safe and do not require boxing and UN boxing situations.
- In terms of performance of application List generics is better than array list.
- Array List can save different type data types.
- List generics we can save only specific data type.
- Array List consumes lots of memory compare to list generics.
- Try creating an abstract class and an Interface and use.
38) What are the difference between interfaces and abstract classes?
- Abstract classes can have implementations for some of its members, but the interface can’t have implementation for any of its members.
- Interfaces cannot have fields where as an abstract class can have fields.
- An interface can inherit from another interface only and cannot inherit from any class; where as an abstract class can inherit from another class or another interface.
- A class can inherit from multiple interfaces at the same time (In this situation C# supports multiple inheritance), where as a class cannot inherit from multiple classes at the same time.
- Abstract class members can have access modifiers where as interface members cannot have access modifiers.
- When do you choose interface over an abstract class or vice versa?
Abstract class implements interface and is extended to to be used. Can also inherit.
- We use abstract class and interface where two or more entities do same type of work but in different ways. Means the way of functioning is not clear while defining abstract class or interface. When functionality of each task is not clear then we define interface. If functionality of some task is clear to us but there exist some functions whose functionality differs object by object then we declare abstract class.
- If we have an implementation that will be the same for all the derived classes, then it is better to go for an abstract class instead of an interface.
- When you have an abstract class, you can share implementation for all derived classes in one central place, and avoid code duplication in derived classes.
- If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.
- If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.
- If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract
- If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.
- An indexer is a member that enables an object to be indexed in the same way as an array.
45) What are the advantages of using interfaces?
- Interfaces facilitate parallel application development
- They are great for implementing Inversion of Control or Dependency Injection.
- Interfaces enable mocking for better unit testing
- Interfaces allow us to develop very loosely coupled systems
- Interfaces also allow us to implement polymorphic behavior
- If the class does not wish to provide Implementation for all the members inherited from the interface. What can we do?
The inherited class has to be marked as abstract.
46) Exception Handling Techniques
There are three ways to handle exceptions/errors in ASP.NET:
1.try-catch block.
2.Error Events.
3.Custom Error Page.
try-catch block
C# provides three keywords try, catch and finally to do exception handling. The try encloses the statements that might throw an exception whereas catch handles an exception if one exists. The finally can be used for doing any clean up process.If any exception occurs inside the try block, the control transfers to the appropriate catch block and later to the finally block.
But in C#, both catch and finally blocks are optional. The try block can exist either with one or more catch blocks or a finally block or with both catch and finally blocks.
If there is no exception occurred inside the try block, the control directly transfers to finally block. We can say that the statements inside the finally block is executed always. Note that it is an error to transfer control out of a finally block by using break, continue, return or goto.
System.Exception is the base class for all exceptions in C#.
Does multiple catch blocks be executed?
Answer: No. Only the appropriate catch block.
Using Error Events
There are three different error events in ASP.NET that can be used in conjunction with Try Catch block so that all exceptions are handled and the user is presented with a user-friendly error message.
1.Page_Error: Occurs when an error occurs within the Web page. This event is in the Web form.
2.Global_Error: Occurs when an error occurs within the application. This event is in the Gloabl.asax file.
3.Application_Error: Occurs when an error occurs within the application. This event is in the Gloabl.asax file.
Methods in the Server object are used to handle the exception in the error events.
1.GetLastError: Gets the last exception that occurred on the server.
2.ClearError: Use this method to handle the exception and stop the error to trigger the subsequent error event or display the error to the user.
Using Custom Error Pages
Use custom error page to handle HTTP exceptions such as page not found, unauthorized access, and so forth. You can specify custom error pages in two places:
1.customErrors section of the web.config file. This setting specifies the application-wide error page to display for unhandled HTTP errors. HTTP errors are identified by the HTTP status code. Include the <error> tag in the customErrors to display a status code-specific error page. Does not work with .htm or .html files. Set the mode attribute to “On” to view the error page locally.
2.errorPage attribute of the @Page directive of the Web form to display the error page for the error generated on the particular Web form.
50) What’s the advantage of using System.Text.StringBuilder over System.String?
StringBuilder is more efficient in the cases, where a lot of manipulation is done to the text. Strings are immutable, so each time it’s being operated on, a new instance is created.
51) What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?
The first one performs a deep copy of the array, the second one is shallow.
52) Classes vs Struct
In .NET, there are two categories of types available named reference type and value type. The reference typed variables resides in heap and uses pointers to some memory locations whereas the value typed variables resides in the stack as value.
Class is reference type and struct is value type. That means, class as a reference type variable contains a pointer or a reference to some memory location where the actual value resides whereas struct as a value type variable contains the entire value.
Class | Struct |
A class is reference type | A struct is a value type |
Class points to a memory location where the object is created | Struct contains the entire struct value |
As class is reference type, copying the object of a class into another variable copies only the reference. That means, you have multiple reference of the same object. | As struct is value type, copying the struct variable to another struct variable copies the entire struct value. |
Resides in the heap as memory location pointing to the actual value present in stack | Resides directly in stack |
Supports inheritance | Does not support inheritance |
Classes and structs support inheritance. Is this statement true or false?
False, only classes support inheritance. structs do not support inheritance.
54) What do you mean by saying a “class is a reference type”?
A class is a reference type means when an object of the class is created, the variable to which the object is assigned holds only a reference to that memory. When the object reference is assigned to a new variable, the new variable refers to the original object. Changes made through one variable are reflected in the other variable because they both refer to the same data.
55)What do you mean by saying a “struct is a value type”?
A struct is a value type mean when a struct is created, the variable to which the struct is assigned holds the struct’s actual data. When the struct is assigned to a new variable, it is copied. The new variable and the original variable therefore contain two separate copies of the same data. Changes made to one copy do not affect the other copy.
56) When do you generally use a class over a struct?
A class is used to model more complex behavior, or data that is intended to be modified after a class object is created. A struct is best suited for small data structures that contain primarily data that is not intended to be modified after the struct is created.
- What’s the difference between the Debug class and Trace class? Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds.
- What does the this window show in the debugger? It points to the object that’s pointed to by this reference. Object’s instance data is shown.
- Can you change the value of a variable while debugging a C# application? Yes, if you are debugging via Visual Studio.NET, just go to immediate window.
- What connections does Microsoft SQL Server support? Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and passwords).
- What’s the role of the DataReader class in ADO.NET connections? It returns a read-only dataset from the data source when the command is executed.
- What does the dispose method do with the connection object? Deletes it from the memory.
- What is a pre-requisite for connection pooling? Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings.
- Explain the three services model commonly known as a three-tier application?
- Presentation (UI), Business (logic and underlying code) and Data (from storage or other sources).
57) What are Shallow Copy and Deep Copy in .NET?
The terms “Shallow Copy ” and “Deep Copy ” which refer to the way the objects are copied, for example, during the invocation of a copy constructor or assignment operator. The deep copy can also be called as member wise copy and the copy operation respects object semantics. For example, copying an object that has a member of type standard string ensures that the corresponding standard string in the target object is copy-constructed by the copy constructor of class string.
Shallow copy: This is nothing but creating a new object, and then copying the non-static fields of the current object to the new object. If a field is a value type then a bit-by-bit copy of the field is performed. If it is a reference type then the reference is copied but not the referred object. Therefore, the original object and its clone refer to the same object.
Deep copy: Deep copy is partially same as shallow copy, but the difference is deep copy copies the whole object and makes a different object, it means it do not refer to the original object while in case of shallow copy the target object always refer to the original object and changes in target object also make changes in original object. It serializes the objects and deserializes the output.