C# Interview Questions - Vikul
C# Interview Questions - Vikul
Purpose of Main() method ? Scenario with writing one more main() method ?
Every program needs an entry point to execute. This Main() method is an entry point where program starts its execution. Main( ) method has some
specification
As C# is a case sensitive language it means Main(), main(), MAIN() these method names a re treated as different.
What are value types and reference types in C# give some examples?
Variables that store the actual data are called as Value Types. Value Types are stored on Stack. They contain the actual valu e. Eg. Int, enum, struct
etc.
Variables that store references to actual data are called as Reference Types. Reference type actual data gets stored on heap. Eg. Cl ass, string, object,
array etc.
Value types gets stored on stack and Reference types gets stored on heap and its reference gets stored on Stack.
By default, Value types cannot hold null values but it can be achieved by using nullable types. Reference types can contain n ull values.
Value types gets destroyed or released from the memory when they go out of scope whereas for reference types requires garbage collector to free
memory.
Escape Sequence
Escape sequence used to provide literal representations of nonprinting characters and charact ers that usually have special meanings, such as the
double quotation mark (").
For example, if we have to print name in double quotes like ““CSharp”” – this will give you compile time error. It can be achieved by using \
operator.
We have to escape special meaning of double quote “ by preceding it with a back slash \ it with “\”CSharp\””
Most used escape sequence are - \b Backspace, \n New line, \t Horizontal tab, \’ single quote, \” double quote, \\ back slash etc etc.
Verbatim literal
If we are working with folder path we use back slash character eg. “C:\Learn\CSharp”.
This will give a compile time error because back slash \ has some special meaning. We can easily escape that by having path like
“C:\\Learn\\CSharp”.
But problem with this is if the path is too long then it will be quite difficult to maintain the path so we can use of verbatim literal to escape meaning of
back slash \ from folder path.
Datatype conversion is nothing but converting one data type to another data type for example converting a int value to a flo at value or vice versa.
Explicit Conversion – When compiler fails for automatic conversion we have to do conversion explicitly.
Converting from a smaller datatype to bigger datatype for example int to float in this case there is no loss of information o r there is no chance of any
exception so compiler will automatically do a conversion which is implicit type conversion. But if we reverse this case let’s say converting a float
value to int then there is definitely a loss of information means int variable will not be able to hold fractional part and a lso there is a chance of
OverflowException. So compiler will not perform implicit conversion and we have to use explicit cast here.
Type casting.
float a = 10;
int b = (int) a;
float a = 10;
int b = Convert.ToInt32(a);
Using as Keyword.
string b = a as string;
We can use Parse and TryParse methods when we need to convert a string to other ty pes like int, bool, float etc.
What is difference between cast operator and Convert class ?
Cast operator handles the exceptions whereas Convert class does not handle and throws the exception. Exception like OverflowE xception,
FormatException etc.
If the number is in a string format you have 2 options - Parse() and TryParse()
Parse() method throws an exception if it cannot parse the value, whereas TryParse() returns a bool indicating whether it succeeded or failed.
We can use Parse() if we are sure the value will be valid, otherwise use TryParse()
Boxing
object o = i;
Unboxing
object o = 100;
int j = (int) o;
Boxing and unboxing are performance wise expensive processes. So it is good to avoid boxing and unboxing if not really needed .
The Object Type is the ultimate base class for all data types in C# Common Type System (CTS). Object is an alias for System.Object class. The object
types can be assigned values of any other types, value types, reference types, predefi ned or user-defined types. However, before assigning values, it
needs type conversion.
When a value type is converted to object type, it is called boxing and on the other hand, when an object type is converted to a value type, it is
called unboxing.
Var type are implicitly types variables. They are introduced in C# 3.0. There is no need to mention the data type when declar ing a variable. A local
variable can be declared implicitly using the var keyword in C#.
We have to compulsorily initialize the value when we are declaring a variable with var. Also its value cannot be null at the time of initialization.
var a= 10;
var z = "CSharp";
The main reason behind introducing var type is the introduction of anonymous types in C#
Var type only used as local variable we cannot use it as class level fields or as method parameters.
Interviewer might extend his question further asking what are anonymous types –
They are extensively used in LINQ expressions whenever you want to return only a few properties from its properties.
eg.
What is difference between var and object type and dynamic keyword?
Var
It is compile time variable and does not require boxing and unboxing. Since Var is a compile time feature, all type checking is done at compile time
only. Once Var has been initialized, you can't change type stored in it.
var test = 10; // after this line test has become of integer ty pe
Object
Each object in C# is derived from object type, either directly or indirectly. It is compile time variable and require boxing and unboxing for conversion
and it makes it slow. You can change value type to reference type and vice versa.
Dynamic
It is run time variable and not require boxing and unboxing. You can assign any value to dynamic and also can change value type stored in same. All
errors on dynamic can be discovered at run time only. We can also say that dynamic is a run time object which can hold any ty pe of data.
The conditional operator (?:) returns one of two values depending on the value of a Boolean expression.
By default value types are non nullable. To make them nullable use ?symbol.
int i = 0 (i is non nullable, so "i" cannot be set to null, i = null will generate compiler error)
int? j = 0 (j is nullable int, so j=null is legal)
Nullable types bridge the differences between C# types and Database types. (for example, in SQL int type can hold null values and in C# by defa ult int
is non nullable.)
If we want to convert from a nullable type to non nullable type then we have to add a check for null value before assignment. So here we can simplify
the assignment by using null coalescing operator ??.
int j = i ?? 0; // as j is non nullable type it can not hold null value. So, here if i value is null then 0 will be assign to j or else i value.
The break statement terminates the closest enclosing loop or switch statement in which it appears.
The continue statement passes control to the next iteration of the enclosing while, do, for, or foreach statement in which it appears.
return
The return statement terminates execution of the method in which it appears and returns control to the calling method. If the method is a void type,
the return statement can be omitted. But we can write return in a method which has void return type if your intention to pass control back to calling
method.
If the return statement is inside a try block and there is finally block exists, then finally will be executed before control returns to the calling method.
What is static and instance members of class?
Static
There will be only a single copy of static members regardless of how many instances of the class are created.
Static methods cannot access any instance members of the class. They can only access the static members of that class.
Pass by Value:- Parameter value changed in called method will not going to be reflect in calling method.
Pass by Reference:- Changes happened in called method will reflect in calling method as the parameter and argument uses the same memory location.
It is mandatory to initialize the value before passing to method.
Output Parameters:- By default method can return only a single value. If we want to return more than one value from a method then we can use output
parameters. It is mandatory to assign values to output parameters before leaving a method.
Parameter Arrays:- If a method has array as input parameter then we can use params keyword with that parameter. Advantages of using parameter
arrays are we can pass comma separated values instead of creating and passing array as argument. Also we can call that method without passing any
parameter i.e. We can achieve optional method parameter using parameter arrays.
What is difference between ref and out parameters ? When to use one over another ?
Output parameters are used when we want to return more than one value from a method. It is mandatory to initialize value before passing a parameter
as ref parameter whereas for output parameter is not mandate. So, if there is need of using that assigned value before callin g method then we can think
of using ref parameter instead out parameter. It is mandatory to assign values to out parameters before control leaves the method whereas it is not
mandate for ref parameter. So when it is required that a method should assign and return values then we can use of out parame ter instead ref
parameter.
Method overloading :- We can overload methods on basis of number of parameters to make optional parameter.
Parameter Arrays :- We can use parameter arrays to make optional parameter as it allows us to call method without passing value for params
parameter.
Default Value :- We can specify default values to parameters to make them optional. If we are specifying default values then it should be from right to
left.
Object Oriented Programming is a programming model where programs are organized around objects and data rather than action an d logic.
A class is complex custom type. Class contains data members and member functions.
A object is a instance of class and also can be considered as a runtime entity of a class.
Constructor is special member function of a class because it has a same na me as that of class. Constructors are automatically called when we create
object of a class. It does not have return type as that of method because main purpose of constructors is to initialize class fields.
There are different types of constructors we can write inside a class like Default Parameter less Constructor, Parameterized Constructor, Copy
Constructor, Static Constructor even a constructor can be private or protected constructor.
Compiler automatically provides a default parameter less constructor but if there is parameterized constructor then we have to explicitly write default
parameter less constructor.
Static constructors are used to initialize static fields of a class. Static constructors are called only once regardless of number of instances of a class.
Static constructors are called before instance constructor gets called on object creation. Static constructors are automatica lly called when we access
static field from class.
Inheritance is the ability to create a class from another class, a parent or base class properties are derived into a child or derived cl ass. Inheritance
provides us code reusability means we can use the existing properties and functionalities from the base class into derived classes. Inheritance provides
a specialization it means a derived class is a specialized class which has all properties of base class as well as its own sp ecific properties. Inheritance
provides extensibility it means we can easily plug a new type without affecting the existing functionalities.
base keyword is used to refer the instance of base class. If we want to access or call constructor or any other instance member fr om base class we can
use base keyword.
We use new keyword to hide the existing base implementation of a method in derived class. The method signature will be same in base cla ss and in
derived class. If we don’t provide new keyword then compiler will gives us a warning that if hiding is intentional then use new keyword. In method
hiding a base class reference variable pointing to a derived class object will invoke base implementation.
internal class A
internal class B : A
public new void Print() // What if we are not specify new keyword ?
internal class C : B
/* Can we override the print method which is marked new in base class ?
:- No. The method should be either abstract or virtual or override in base class in order to override it in derived class
*/
{
Console.WriteLine("Class C Print Method");
b.Print();
A a = new B();
a.Print(); // Which method will get called ? class A Print method called.
A same method name can have different forms on basis of number of parameters, order of parameters, types of parameters and kinds of parameters.
Here types means any data types like int, float, double etc and kinds meaning out, ref, params.
Can method overloaded on basis of just return type ? if no, then why?
No. Method cannot be overloaded just on basis of return type. Return type is not considered in method signature while method overloading.
This behaviour is by design and it is because to avoid confusion of a developer that what will be the output of the method if the method is same and just
changed with the return type.
return 10;
{
return 10;
At compile time both ref and out refers as same and internally both works same. So compiler does not allow us to overload a m ethod just on basis of
ref and out parameter.
//Cannot define overloaded method 'Print' because it differs from anothe r method only on ref and out
We cannot overload a method just on basis of params keyword. Compiler does not find any difference in normal array parameter and a parameter
array at compile time.
//already defines a member called 'Print' with the same parameter types
A base class reference variable pointing to a derived class object will invoke a derived class overridden method.
In order to override a method in derived class that method should be virtual or abstract or override in base class.
Method overriding is called as runtime polymorphism because CLR checks the type of object and call particular version of meth od at runtime.
What is difference between method hiding and method overriding? Scenarios of calling metho ds with multiple object creation scenarios?
We hide a method using new keyword whereas we use override keyword to override a method.
For method overriding it is mandatory that the method should be override virtual or abstract in base class whereas for meth od hiding it is not
mandatory.
In method hiding, a base class reference variable pointing to a derived class object will invoke a base class implementation whereas in method
overriding a base class object pointing to a derived class object will invoke a de rived class overridden implementation.
Method overloading and method overriding both are the types of polymorphism.
Method overloading is a compile time polymorphism because at compile time only it is known that which overloaded method will get invoke on
execution.
Method overriding is a runtime polymorphism because which method will get called is decided at runtime based on the type of o bject.
Association
Association is a relationship between the objects. Just like Inheritance defines the ‘is a’ relationship, Association defines ‘has a’ or using
relationships. In short, Association means an object “uses” another object.
Aggregation
For example, departments and employees, a department has many employees b ut a single employee is not associated with multiple departments. In this
case both the objects have their own life cycle. Employees may exist without a department. Here, department can be called an owner object and the
employee can be called a child object.
Composition
Composition is special type of Aggregation. It is a strong type of Aggregation. In this type of Aggregation the child object does not have their own life
cycle. The child object's life depends on the parent's life cycle. Only the parent obj ect has an independent life cycle. If we delete the parent object then
the child object(s) will also be deleted. We can define the Composition as a "Part of" relationship.
For example, the company and company location, a single company has multiple locatio ns. If we delete the company then all the company locations
are automatically deleted. The company location does not have their independent life cycle, it depends on the company object' s life (parent object).
What are Properties ? Why should we use properties ? What is autoimplemented properties?
Properties are used just like they are public fields of a class. Properties are used to encapsulate and protect the private fields. We can write custom
logic to validate the user data before it is actually assigned to or retrieved from private fields.
Using get and set access modifiers, we can create Read Only, Write Only and Read Write Properties depending on our requiremen t.
Auto implemented properties were introduced in C#3.0, with this feature we do not need to declare a separate private field for a property. Framework
automatically creates a private field for the declared property. Eg. Public string Name{ get; set; }
Indexers are used to design our class objects indexed based just like an array.
We create Indexers by using “this” keyword. We can overload the indexers just like we overload a method.
In real time, Session object, DataTable object, Rows Object uses indexers to access the values.
A struct is a value type and they get stored on the stack whereas class is reference type and they get stored on the heap.
Struct gets immediately destroyed from the memory once they go out of scope whereas for class only reference variable gets de stroyed after it goes out
of scope and the actual object get released by garbage collector.
When we copy one struct to another struct a new struct gets created and any modification on one struct will not going to affe ct the other struct whereas
when we copy one class to another class we get a new copy of reference variable which actually points to same object on heap. So any change in one
class object will going to affect on other class object.
Struct cannot have explicit parameter less constructor whereas a class can have.
A class or struct cannot inherit from another struct because struct are sealed type.
What is encapsulation and abstraction ? When abstraction and encapsulation comes in proj ect development ?
Encapsulation is a concept of hiding unnecessary data from outside world. It binds data and functions into a single unit whic h is called as class.
If we talk in terms of coding perspective, public fields shows abstraction and private fields shows encapsulation.
Interfaces are just like classes but they just have declarations and not definitions.
Interfaces cannot be instantiated but an interface reference variable can point to a class which implements that interface.
If a class implementing an interface it is mandatory to provide imp lementation to all of the interface members.
Interfaces members are by default public even we cannot specify public access specifier explicitly to any of its member.
Multiple class inheritance is not possible in C# but we can achieve it with interfaces.
Interfaces are used to implement SOLID principles and Design patterns.
What is explicit interface implementation ? When there will be need of implementing interface explicitly.
When we are implementing 2 or more interfaces in a class and those interfaces are having same method signature. Then we have to implement those
interfaces explicitly in order to give implementation to all of the interfaces.
We have to prefix method name with interface name while implementing interface explicitly.
This implemented methods are public by default. We cannot specify any other access modifier even a public.
Creating a class object and then type casting as interface and invoking a method.
Abstract classes are created with abstract keyword. They are just like normal classes but they can have both abstract and non -abstract members.
Abstract members meaning members with just declarations.
Abstract classes cannot be instantiated but an abstract class reference variable can point to a derived class object.
Though we cannot create instance of abstract class but its reference variable can point to a derived class object.
Abstract class constructors get called before derived class constructo r call.
Sealed class or struct are prevented from inheritance. It means Sealed classes cannot be used as base class.
What is difference between interface and abstract class? When to use interface over abstract class or vice versa.
Interface cannot have definition for any of its member whereas abstract class can have non -abstract members.
Interfaces cannot have fields whereas abstract class can contain field.
Interface members access modifiers are public by default and we cannot specify any other even a public whereas abstract class members a ccess
specifers can be changed.
As Interfaces does have just declarations and also it does not contain fields so if there is situation that all the derived classes has different
implementation but you have to provide same method signature then we can go with interfaces.
An abstract class can have fields and definitions for its members so if there is a situation that few of the derived classes sharing same implementation
then we can think of using abstract class instead of interface.
Let’s say we have one class A which is derived by two classes B and C. Class B and C has overridden method which was marked v irtual in class A.
Now if we derive class B and C in a new class D and we are not providing any implementation in class D.
So, if we create an object of class D then which method implementation should get call here from class B or class C. There wi ll be an ambiguity in
calling 2 different copies of overridden method. This problem is called as Diamond Problem.
We can achieve multiple class inheritance using interfaces. [Interviewer can ask to write a code snippet here.]
Protected – It is accessible within containing type as well as in derived type in same assembly or from different assembly.
Protected Internal – It is accessible anywhere within same assembly and from derived type in different assembly.
We can have only public and internal access modifiers with types whereas we can use all the 5 access modifiers with type members.
Internal access modifiers are accessible from anywhere within the same assembly. We cannot access them outside assembly.
Protected internal is can be considered as combination of protected and internal access specifiers means it is accessible any where from the containing
assembly and from derived type from outside assembly.
It is always a bad practice in showing yellow screen to end user which contains some application specific information.
This information is meaningless for a normal user whereas useful for a hacker to hack your application.
Can a try block have multiple catch block ? Scenario of using Exception classes while using multiple catch blocks ?
But as all exception classes are derived from Exception base class we have to specify Exception class in the end catch block. If we specify it at the top
then we will get compiler error.
So if we want more than one catch block then all specific exception classes like FileNotFoundException, NullReferenceExceptio n etc should be
mentioned before Exception class catch block.
Finally block is guaranteed to be executed in both the cases if there is error occurs or not. Also it gets executed if there is any error occurs in catch
block.
So we can use finally block to close the open connection or if we want to explic itly free the resources.
[Scenarios can be asked based on return statement or using Response.Redirect, Server.Transfer, Server.Execute by writing them in try catch and
finally blocks.]
StringBuilder objects are mutable so they offer better performance than string objects when heavy string manipulation is involved.
What are enums? What are usage of enums?
If a program uses set of integral numbers we can replace them with enums. This will increase the code readability and maintainability.
What is default underlying type to enum? Can we change its underlying type to some other type?
We can anytime change underlying type to any other integral datatypes like short, int16 etc depending on the size we want to store.
enum is a keyword use to create enumerations whereas Enum class contains static methods like GetValues(), GetNames() which can be used to list
enum underlying type values and their names.
What are all default methods comes with every type in dot net? From where they are derived? Can we override them?
All types in dot net directly or indirectly derived from System.Object class.
So with all types by default we get 4 methods GetType(), ToString(), Equals() and GetHashCode() which are actually inherited from System.Object
class.
All these 4 methods are virtual in Object class so we can anytime override them in different types.
Console.WriteLine(number.GetType());
Both the methods are used to get the type of the current instance.
For typeof method type is known as compile time whereas GetType() method is used to get exact type of current instance at run time.
GetType() method is invoked with instance whereas typeof method expects the type.
Why there is need of overriding ToString() method?
When we invoke ToString() method on any simple types it gives us the string representation of that current type.
But if we invoke ToString() method on Complex types like Customer, Employee it gives us the fully qualified name of the type that means namespace
name followed by type name.
So to give a meaningful string representation for complex types we can override ToString() method.
Why to override Equals() method? Is there is any warning/error associates with just overriding Equals method? If yes, how to fix it?
Equals() method works fine when there are value types but when it comes to reference types it checks only reference equality and not value equality.
So we can override this Equals() method to check value equality for reference types.
There is one warning when we override Equals() method and that is we have to override GetHashCode() method also. Thi s method is helps to generate
unique hash codes.
All arithmetic operators works fine when there are simple types as operands like int, string etc. But when it comes to comple x types like Customer
class, Employee class it gives compile time error saying operator cannot apply on type like Customer.
If we use == operators with complex types it just check reference equality and not value equality. In order to achieve value equality we have to
override == methods.
Delegates signature should get match with method signature that’s why it is calle d as type safe.
If the methods has return type or out parameter then the last method value get ret urned from delegate.
Anonymous methods are nothing but methods without name. They were introduced in C#2.0.
Anonymous methods allows us to create delegate instance without having a sep arate method.
Extension Methods :
Extension methods are used to extend the functionality of any existing type.
These methods are public static methods and its first parameter is prefixed with this keyword. It is mandatory to write extension method in public static
class.
What is lambda expression? Interviewer can ask to write a small program using lambda expressions.
Lambda expression are simplified way to write LINQ queries. They were introduced in C#3.0.
[Interviewer can ask to write lambda expressions based on some customer list to find particular customer data we have to use LINQ extension methods
and lambda expression to achieve this]
There is only single difference between them is for anonymous methods if parameters are not used then we can omit them but for lambda expression we
cannot omit the parameters list.
Apart from these types we have few generic delegates which extensively used in LINQ methods.
Action Delegate – Delegate has type T as input parameter and void as return type.
Predicate Delegate – Delegate has type T as input parameter and bool as return type.
Func Delegate – This delegate has around 17 overloads. Which takes T as input parameters and T as output parameter.
Generics allows us to design classes and methods decoupled from the data types.
Which avoid boxing and unboxing operations and offers better performance.
List<T>, Dictionary<T>, Stack<T>, Queue<T> are few examples of generic collections classes.
ArrayList, HashTable, SortedList, Stack, Queue are few examples of non generic collections classes.
ArrayList is a non-generic collection class and resides in System.Collection namespace whereas List is a generic class and resides in
System.Collections.Generic namespace.
ArrayList is object based it is not type safe and there is associated boxing and unb oxing operations which is overhead to performance.
Whereas List is type safe and there is no boxing and unboxing operations which actually helps to improve system performance.
HashTable is a non-generic collection class and resides in System.Collection namespace whereas Dictionary is a generic class and resides in
System.Collections.Generic namespace.
HashTable is object based it is not type safe and there is associated boxing and unboxing operations which is overhead to performance.
Whereas Dictionary is type safe and there is no boxing and unboxing operations which actually helps to improve system perform ance.
Being type safety there will not be any overhead of operations like boxing unboxing so it helps to improve the performance.
What is Tuple?
Tuple can be used as return type of a method whereas we cannot use anonymous types as return type.
What is reflection? Advantages and disadvantages? Remember some imp classes fr om System.Reflection namespace.
Reflection is the ability of inspecting an assemblies metadata at runtime. It is used to find all types in an assembly and dy namically invoke methods of
an assembly.
We can use reflection to dynamically create an instance of a type about which we don’t have any information at compile time. So, reflection enables we
to use code that is not available at compile time.
Reflections are extensively used by IDE or UI designer, for ASP.NET Server controls the properties window uses reflection to show all properties of
control.
All classes are present in System.Reflection namespace. We use Activator class from this namespace to create instance of a type.
Early binding gives errors at compile time with late binding there is a risk of runtime exceptions.
Early binding is much better for performance and should always be prepared over late binding. Late binding is used only when we are not aware about
the objects at compile time.
In eager loading all the objects are initialized in memory as soon as the objects are created.
In Lazy loading we delay the loading of the objects until the point where we need it. So, Lazy loading is nothing but on demand object loading rather
than loading object unnecessary.
Partial classes allow us to split a class into 2 or more files. All these parts then combined into a single class, when the application is compiled.
Visual studio uses partial classes to separate automatically generated system code .aspx.designer.cs file from the developer’s code .aspx.cs file.
[If interviewer asks for rules then explain below set of rules]
Multiple class inheritance is not possible in C# so different parts should not inherit different base classes.
What are partial methods? Anything can be asked related to rules followed during creating partial methods?
Partial method created using partial keyword and it has two parts – the Definition and the implementation.
Partial methods are private by default. We cannot specify any other modifier even private.
Partial method implementation is optional. If we not provide implementation then complier removes its declaration as well as all the calls.
Partial method return type must be void. Giving any other type gives compile time error.
IEnumerable
The IEnumerable<T> is used to iterate a read only collection. It has only one method GetEnumeartor() which allows you to iter ate the read only
collection using a foreach loop. It only iterates in the forward direction.
It does not contain any other functions like add, remove, count etc. So you cannot add, remove objects in IEnumerable collection.
IQueryable
IQueryable<T> allows you to execute a query against a specific data source where in type of data is not specified.
It extends the IEnumerable, hence it allows you to iterate over collection using the foreach statement. All the properties of IQueryable are read only.
IQueryable<T> extends IQueryable and the IEnumerable.
IComparable
Defines a generalized type-specific comparison method that a value type or class implements to order or sort its instances.
By default, all simple types implements IComparable interface so it is possible to invoke Sort me thod on simple type collections.
Whereas for Complex types collection we have to implement IComparable’s CompareTo method in order to Sort the collection.
IComparer
Sort method has overloads where its expects a IComparer type. So we can implement IComparer interface to the class and we can sort it on basis of
any of its property.
Collections classes Sort method has 4 different overloads. One of the overload expects type o f Comparison delegate object.
We can write a method as delegate signature and we can pass this method to delegate instance. This is one of the way to achie ve sorting of complex
types collection.
How to restrict a class for instantiation?
We can restrict a class for its instantiation by making that class as a static class or we can write a private constructor in that class.
When we write a private or protected constructor in a class we cannot create instance of that class from outside of that class.
We create the instance of a class in that class itself. We use public static method to expose the instance.
Singleton pattern ensures that there will be single copy of object throughou t the application and it provides a global point to access that instance.
A Static class does not have non static or instance members whereas in Singleton class we can have both static and instance members.
Singleton class can implements interface whereas static class cannot implement interface.
We cannot pass static class to a method whereas we can pass single instance of singleton class to a method.
We can dispose the object of singleton class but not of static class.
class Singleton
private Singleton()
if (_instance == null)
}
return _instance;
Singleton s1 = Singleton.Instance();
Singleton s2 = Singleton.Instance();
[Please note that here s1 == s2 will be true as both are referring to same object.]
Inheritance scenarios - like multilevel inheritance with new and override keywords.
Let’s say there are 3 classes A, B and C. Class B is inheriting cla ss A and class C is inheriting class B.
There will be a method which will be virtual in class A and it will be hidden by class B and C with new keyword. Then which m ethods will get called
with below set of objects.
A a1 = new B();
A a2 = new C();
B b1 = new C();
Same example can be replaced with override keyword or combination of new and override methods. We have to think on the type o f object and give the
answers.
Static fields have a single copy irrespective of number of instances of a class. They are accessed with class name.
Constant
– ReadOnly
ReadOnly fields are also similar to constant variables but we can change its value at runtime through non static constructors.
We can customize iteration through a collection without creating a temporary collection. Whic h will helps us to save some memory.