Abstract Class
Abstract Class
Abstract Class
Abstract classes are useful when you need a class for the purpose of inheritance
and polymorphism, but it makes no sense to instantiate the class itself, only its
subclasses. They are commonly used when you want to define a template for a
group of subclasses that share some common implementation code, but you also
want to guarantee that the objects of the superclass cannot be created.
For instance, let's say you need to create Dog, Cat, Hamster and Fish objects. They
possess similar properties like color, size, and number of legs as well as behavior so
you create an Animal superclass. However, what color is an Animal? How many legs
does an Animal object have? In this case, it doesn't make much sense to instantiate
an object of type Animal but rather only its subclasses.
Abstract classes also have the added benefit in polymorphismallowing you to use
the (abstract) superclass's type as a method argument or a return type. If for
example you had a PetOwner class with a train() method you can define it as taking
in an object of type Animal e.g. train(Animal a) as opposed to creating a method for
every subtype of Animal.
1. Generics refer to the technique of writing the code for a class without specifying the data type(s) that
the class works on.
2. You specify the data type when you declare an instance of a generic class.
3. This allows a generic class to be specialized for many different data types while only having to write the
class once.
Arraylist is not strongly typed.
Arrays are strongly typed.
Allows you to write code/use library methods which are type-safe, i.e. a List<string> is guaranteed
to be a list of strings.
As a result of generics being used the compiler can perform compile-time checks on code for type
safety, i.e. are you trying to put an int into that list of strings? Using an ArrayList would cause that to be
a less transparent runtime error.
Faster than using objects as it either avoids boxing/unboxing (where .net has to convert value
types to reference types or vice-versa) or casting from objects to the required reference type
It's much less of an issue now than it was prior to generics. Now, for example, we can use:
{
}
Console.WriteLine(this._value);
Constructor in C#:
Constructor(s) in a class is/are special methods which get called automatically when an object of a class
is created. Constructors are specially used to initialize data members. There are different types of
constructors you can write in a class 1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
4. Static Constructor
Default Constructor
When you do not declare any constructor, the class will call its default constructor which has a default
public access modifier. The default constructor is a parameter less constructor which will be called by a
class object.
Let's see an example of a Default Constructor This default constructor will be executed whenever the class is initialized Person p = new Person();
Note: If the class is abstract, then the accessibility of the default constructor is protected. Otherwise, the
accessibility for the default constructor is public
Parameterized constructors
Now lets see parameterized constructors. You can also call it as constructor overloading. Default
constructors always initialize the objects with the same values. In case you want to initialize the class with
different values, you can use Parameterized constructors.
public class Person
{
private int m_PersonID;
Copy Constructor
Now let's see an example of Copy Constructor. Copy constructor is the parameterized constructor which
takes a parameter of the same type. It allows you to initialize a new object with the existing object values.
public class Person
{
private int m_PersonID;
private string m_FirstName, m_LastName, m_City;
public Person()
{
m_PersonID = 19929;
m_FirstName = "No First Name";
m_LastName = "No Last Name";
m_City = "No City";
}
public Person(string firstName,string lastName)
{
m_FirstName = firstName;
m_LastName = lastName;
}
//copy constructor
public Person(Person person)
{
m_PersonID = person.m_PersonID;
m_FirstName = person.m_FirstName;
m_LastName = person.m_LastName;
m_City = person.m_City;
}
}
Heres an example:
// Instance constructor.
Person p1 = new Person(1, "DotNet", "Curry", "Pune");
// Copy Constructor
Person p2 = new Person(p1);
Static Constructors
Static constructor is used to initialize the static data members of the class. Static constructor is only called
once while creation of the first instance of the class. After that, no instance of a class will call the static
constructor. You can also use static constructor to execute some code of the class which must be
executed only once.
public class Person
{
static Person()
{
//Static Members
}
}
In inheritance, the calling of the constructor starts from the parent class.
Let's see how to use these constructors static void Main(string[] args)
{
Person p1 = new Person();//This will call Default Constructor
Person p2 = new Person("Pravin", "D");//This will call two parameterized Constructor
Person p3 = new Person(p2);//This will call Copy Constructor
}
It is worth mentioning that you can also create a private constructor, which is generally used in classes
that contain static members only. If you create a private constructor, you cannot create an instance of a
class.
class Person
{
// Private Constructor:
private Person() { }
...
---Note
Parent class= Base class
Child class= Derived class
Overloading:
Overloading is when you have multiple methods in the same scope, with the same name but different
signatures.
//Overloading
public class test
{
public void getStuff(int id)
{}
public void getStuff(string name)
{}
}
Overriding:
Overriding is a principle that allows you to change the functionality of a method in a child class.
//Overriding
public class test
{
public virtual void getStuff(int id)ssss
{
//Get stuff default location
}
}
public class test2 : test
{
public override void getStuff(int id)
{
//base.getStuff(id);
//or - Get stuff new location
}
}
Abstract class:
Use an abstract class to provide some concrete implementation but not allow instantiation. You can
always instantiate an ordinary class which doesn't make sense if it can't stand alone. At the same time, an
interface might not be enough if there's a concrete implementation that's identical in all implementing
classes. An abstract class is just enough.
Interface: contract only, no implementation, no instantiation
Abstract class: contract, some implementation, no instantiation
Class: contract, implementation, instantiation
DataSet:
1.DataSet is a disconnected orient architecture that means there is no need of active connections during
work with datasets and it is a collection of DataTables and relations between tables. It is used to hold
multiple tables with data. You can select data form tables, create views based on table and ask child rows
over relations. Also DataSet provides you with rich features like saving data as XML and loading XML
data.
protected void BindGridview()
{
SqlConnection conn = new SqlConnection("Data Source=abc;Integrated Security=true;Initial
Catalog=Test");
conn.Open();
SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location FROM
Users", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvUserInfo.DataSource = ds;
gvUserInfo.DataBind();
}
DataAdapter:
1.DataAdapter will acts as a Bridge between DataSet and database.
2.This dataadapter object is used to read the data from database and bind that data to dataset.
Dataadapter is a disconnected oriented architecture.
Check below sample code to see how to use DataAdapter in code:
protected void BindGridview()
{
SqlConnection con = new SqlConnection("Data Source=abc;Integrated Security=true;Initial
Catalog=Test");
conn.Open();
SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location FROM
Users", conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvUserInfo.DataSource = ds;
gvUserInfo.DataBind();
}
Lets you close the connection as soon it's done loading data, and may even close it for you
automatically
You can iterate over it as many times as you need, or even look up a specific record by index
DataTable
DataTable represents a single table in the database. It has rows and columns. There is no much
difference between dataset and datatable, dataset is simply the collection of datatables.
protected void BindGridview()
{
SqlConnection con = new SqlConnection("Data Source=abc;Integrated Security=true;Initial
Catalog=Test");
conn.Open();
SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location FROM
Users", conn);
SqlDataReader:
Holds the connection open until you are finished (don't forget to close it!).
Can typically only be iterated over once
Is not as useful for updating back to the database
On the other hand, it:
Only has one record in memory at a time rather than an entire result set (this can be huge)
Is about as fast as it you can get for that one iteration
Allows you start processing results sooner
SqlDataAdapter/DataSet
Lets you close the connection as soon it's done loading data, and may even close it for you
automatically
All of the results are available in memory
You can iterate over it as many times as you need, or even look up a specific record by index
Has some built-in faculties for updating back to the database
So really it depends on what you're doing, but I tend to prefer a DataReader until I need something that's
only supported by a dataset. SqlDataReader is perfect for the common data access case of binding to a
read-only grid.
16) Can we execute multiple catch blocks in C#?
No. Once any exception is occurred it executes specific exception catch block and the control comes out.
18) What is the difference between finalize and finally methods in C#?
Finalize This method is used for garbage collection. So before destroying an object this method
is called as part of clean up activity.
Finally This method is used for executing the code irrespective of exception occurred or not.
19) What is the difference between throw ex and throw methods in C#?
throw ex will replace the stack trace of the exception with stack trace info of re throw point.
23) Mention the assembly name where System namespace lies in C#?
Assembly Name mscorlib.dll
24) What are the differences between static, public and void in C#?
Static classes/methods/variables are accessible throughout the application without creating instance.
Compiler will store the method address as an entry point.
Public methods or variables are accessible throughout the application.
Void is used for the methods to indicate it will not return any value.
25) What is the difference between out and ref parameters in C#?
out parameter can be passed to a method and it need not be initialized where as ref parameter has to
be initialized before it is used.
decimal
int
byte
enum
double
long
float
class
string
interface
object
32) In try block if we add return statement whether finally block is executed in C#?
Yes. Finally block will still be executed in presence of return statement in try block.
StringBuilder is mutable, which means once object for stringbuilder is created, it later be modified
either using Append, Remove or Replace.
String is immutable and it means we cannot modify the string object and will always create new
object in memory of string type.
37) How we can sort the array elements in descending order in C#?
Sort() method is used with Reverse() to sort the array in descending order.
NullReferenceException
ArgumentNullException
DivideByZeroException
IndexOutOfRangeException
InvalidOperationException
StackOverflowException etc.
Generics in c# is used to make the code reusable and which intern decreases the code redundancy and
increases the performance and type safety.
Namespace System.Collections.Generic is available in C# and this should be used over
System.Collections types.
Delegates are type safe pointers unlike function pointers as in C++. Delegate is used to represent the
reference of the methods of some return type and parameters.
43) What are the types of delegates in C#?
Below are the uses of delegates in C#
Single Delegate
Multicast Delegate
Generic Delegate
44) What are the three types of Generic delegates in C#?
Below are the three types of generic delegates in C# -
Func
Action
Predicate
45) What are the differences between events and delegates in C#?
Main difference between event and delegate is event will provide one more of encapsulation over
delegates. So when you are using events destination will listen to it but delegates are naked, which works
in subscriber/destination model.
Callback Mechanism
Asynchronous Processing
Multicasting
48) What is Nullable Types in C#?
Variable types does not hold null values so to hold the null values we have to use nullable types. So
nullable types can have values either null or other values as well.
Eg: Int? mynullablevar = null;
49) Why to use Nullable Coalescing Operator (??) in C#?
Nullable Coalescing Operator can be used with reference types and nullable value types. So if the first
operand of the expression is null then the value of second operand is assigned to the variable. For
example,
double? myFirstno = null;
double mySecno;
mySecno = myFirstno ?? 10.11;
50) What is the difference between as and is operators in C#?
is operator is used for checking the object with type and this will return a Boolean value.
53) Is C# code is unmanaged or managed code?
C# code is managed code because the compiler CLR will compile the code to Intermediate Language.
54) Why to use lock statement in C#?
Lock will make sure one thread will not intercept the other thread which is running the part of code. So
lock statement will make the thread wait, block till the object is being released.
ue1");
myHashtbl.Add("2", "TestValue2");
56) How to check whether hash table contains specific key in C#?
Method ContainsKey can be used to check the key in hash table. Below is the sample code for the
same
Eg: myHashtbl.ContainsKey("1");
57) What is enum in C#?
enum keyword is used for declaring an enumeration, which consists of named constants and it is called
as enumerator lists. Enums are value types in C# and these cant be inherited. Below is the sample code
of using Enums
Eg: enum Fruits { Apple, Orange, Banana, WaterMelon};
58) Which are the loop types available in C#?
Below are the loop types in C# For
While
Do.. While
59) What is the difference between continue and break statements in C#?
continue statement is used to pass the control to next iteration. This statement can be used with
while, for, foreach loops.
break statement is used to exit the loop.
60) Write a sample code to write the contents to text file in C#?
Below is the sample code to write the contents to text file
Using System.IO;
File.WriteAllText(mytextfilePath, MyTestContent);
61) What you mean by boxing and unboxing in C#?
Boxing This is the process of converting from value type to reference type. For example,
int myvar = 10;
object myObj = myvar;
UnBoxing Its completely opposite to boxing. Its the process of converting reference type to value type.
For example,
int myvar2 = (int)myObj;
62) Explain Partial Class in C#?
Partial classes concept added in .Net Framework 2.0 and it allows us to split the business logic in multiple
files with the same class name along with partial keyword.
63) Explain Anonymous type in C#?
This is being added in C# 3.0 version. This feature enables us to create an object at compile time. Below
is the sample code for the same
Var myTestCategory = new { CategoryId = 1, CategoryName = Category1};
64) Name the compiler of C#?
C# Compiler is CSC.
65) Explain the types of unit test cases?
Below are the list of unit test case types
set
{
myArr[t] = value;
}
}
}
70) What are the collection types can be used in C#?
Below are the collection types in C#
ArrayList
Stack
Queue
SortedList
HashTable
Bit Array
71) Explain Attributes in C#?
Attributes are used to convey the info for runtime about the behavior of elements like methods,
classes, enums etc.
Attributes can be used to add metadata like comments, classes, compiler instruction etc.
72) List out the pre defined attributes in C#?
Below are the predefined attributes in C# -
Conditional
Obsolete
Attribute Usage
73) What is Thread in C#?
Thread is an execution path of a program. Thread is used to define the different or unique flow of control.
If our application involves some time consuming processes then its better to use Multithreading., which
involves multiple threads.
74) List out the states of a thread in C#?
Below are the states of thread
Unstarted State
Ready State
Dead State
75) Explain the methods and properties of Thread class in C#?
Below are the methods and properties of thread class
CurrentCulture
CurrentThread
CurrentContext
IsAlive
IsThreadPoolThread
IsBackground
Priority
76) What is a class ?
A class is the generic definition of what an object is. A Class describes all the attributes of the object, as
well as the methods that implement the behavior of the member object. In other words, class is a template
of an object. For ease of understanding a class, we will look at an example. In the class Employee given
below, Name and Salary are the attributes of the class Person. The Setter and Getter methods are used
to store and fetch data from the variable.
public class Employee
{
private String name;
private String Salary;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getSalary ()
{
return Salary;
}
public void setSalary (String Salary)
{
this. Salary = Salary;
}
}
Public When a method or attribute is defined as Public, it can be accessed from any code in the
project. For example, in the above Class Employee getName() and setName() are public.
Private - When a method or attribute is defined as Private, It can be accessed by any code within
the containing class only. For example, in the above Class Employee attributes name and salary can
be accessed within the Class Employee Only. If an attribute or class is defined without access modifiers,
it's default access modifier will be private.
Protected - When attribute and methods are defined as protected, it can be accessed by any
method in the inherited classes and any method within the same class. The protected access modifier
cannot be applied to classes and interfaces. Methods and fields in a interface can't be declared
protected.
Internal If an attribute or method is defined as Internal, access is restricted to classes within the
current project assembly.
When methods are created with the same name, but with different signature its called overloading. For
example, WriteLine method in console class is an example of overloading. In the first instance, it takes
one variable. In the second instance, WriteLine method takes two variable.
Console.WriteLine(x);
Console.WriteLine("The message is {0}", Message);
Different types of overloading in C# are
Constructor overloading
Function overloading
Operator overloading
83) What is Constructor Overloading in C# .net ?
In Constructor overloading, n number of constructors can be created for the same class. But the
signatures of each constructor should vary. For example
public class Employee
{
public Employee()
{}
public Employee(String Name)
{}
}
84) What is Function Overloading in C# .net ?
In Function overloading, n number of functions can be created for the same class. But the signatures of
each function should vary. For example
public class Employee
{
public void Employee()
{}
public void Employee(String Name)
{}
}
85) What is Operator Overloading in C# .net ?
We had seen function overloading in the previous example. For operator Overloading, we will have a look
at the example given below. We had defined a class rectangle with two operator overloading methods.
class Rectangle
{
private int Height;
private int Width;
This is in line with the OOPS Concept that an external user should know about what an object does. How
it does it, should be decided by the program.
In the above example, we had used getters and setters to set value for MinSalary. The idea behind this is
that, private field minimumSalary is an important part of our classes. So if we give a third party code to
have complete control over the field without any validation, it can adversely affect the functionality. So if a
user set a negative value for MinSalary, we can put a validation in the set method to avoid negative values
as shown below
set
{
if(value > 0)
{
minSalary = value;
}
}
87) Explain Inheritance in C# ?
In object-oriented programming (OOP), inheritance is a way to reuse code of existing objects.
In inheritance, there will be two classes - base class and derived classes. A class can inherit attributes
and methods from existing class called base class or parent class. The class which inherits from a base
class is called derived classes or child class. For more clarity on this topic, let us have a look at 2 classes
shown below. Here Class Car is Base Class and Class Ford is derived class.
class Car
{
public Car()
{
Console.WriteLine("Base Class Car");
}
public void DriveType()
{
Console.WriteLine("Right Hand Drive");
}
}
class Ford : Car
{
public Ford()
{
Console.WriteLine("Derived Class Ford");
}
public void Price()
{
Console.WriteLine("Ford Price : 100K $");
}
}
When we execute following lines of code ,
Ford CarFord = new Ford();
CarFord.DriveType();
CarFord.Price();
Output Generated is as given below.
Base Class Car
Derived Class Ford
Right Hand Drive
Ford Price : 100K $
What this means is that, all the methods and attributes of Base Class car are available in Derived Class
Ford. When an object of class Ford is created, constructors of the Base and Derived class get invoked.
Even though there is no method called DriveType() in Class Ford, we are able to invoke the method
because of inheriting Base Class methods to derived class.
88) Can Multiple Inheritance implemented in C# ?
In C#, derived classes can inherit from one base class only. If you want to inherit from multiple base
classes, use interface.
89) What is Polymorphism in C# ?
The ability of a programming language to process objects in different ways depending on their data type
or class is known as Polymorphism. There are two types of polymorphism.
class Car
{
public Car()
{
Console.WriteLine("Base Class Car");
}
public virtual void DriveType()
{
Console.WriteLine("Right Hand Drive");
}
}
class Ford : Car
{
public Ford()
{
Console.WriteLine("Derived Class Ford");
}
public void Price()
{
Console.WriteLine("Ford Price : 100K $");
}
public override void DriveType()
{
Console.WriteLine("Right Hand ");
}
}
When following lines of code get executed
Car CarFord = new Car();
CarFord.DriveType();
CarFord = new Ford();
CarFord.DriveType();
Output is as given below.
Base Class Car
public Car()
{
Console.WriteLine("Base Class Car");
}
public abstract void DriveType();
}
class Ford : Car
{
public void DriveType()
{
Console.WriteLine("Right Hand ");
}
}
Method DriveType get implemented in derived class.
94) What is Sealed Classes in c# ?
If a class is defined as Sealed, it cannot be inherited in derived class. Example of a sealed class is given
below.
public sealed class Car
{
public Car()
{
Console.WriteLine("Base Class Car");
}
public void DriveType()
{
Console.WriteLine("Right Hand ");
}
}
95) What is an Interface in C# ?
An interface is similar to a class with method signatures. There wont be any implementation of the
methods in an Interface. Classes which implement interface should have an implementation of methods
defined in the abstract class.
Console.WriteLine("Power Break");
}
public void WheelType()
{
Console.WriteLine("Bridgestone");
}
}
97) What is a Destructor in C# ?
Destructor is a special method that get invoked/called automatically whenever an object of a given class
gets destroyed. Main idea behind using destructor is to free the memory used by the object.
In programming language errors can be divided into three categories as given below1.
Syntax Errors
Syntax errors occur during development, when you make type mistake in code. For example, instead of
writing while, you write WHILE then it will be a syntax error since C# is a case sensitive language.
1.
2.
3.
4.
5.
6.
2.
bool flag=true;
WHILE (flag) //syntax error, since c# is case sensitive
{
//TO DO:
}
Runtime Errors (Exceptions)
Runtime errors occur during execution of the program. These are also called exceptions. This can be
caused due to improper user inputs, improper design logic or system errors.
1. int a = 5, b = 0;
2. int result = a / b; // DivideByZeroException
Exceptions can be handled by using try-catch blocks.
3.
Logical Errors
Logic errors occur when the program is written fine but it does not produce desired result. Logic errors are
difficult to find because you need to know for sure that the result is wrong
1. int a = 5, b = 6;
2. double avg = a + b / 2.0; // logical error, it should be (a + b) / 2.0
1. What is C#?
C# is the best language for writing Microsoft .NET applications. C# provides the rapid application
development found in Visual Basic with the power of C++. Its syntax is similar to C++ syntax and meets
100% of the requirements of OOPs like the following:
Abstraction
Encapsulation
Polymorphism
Inheritance
Introduction to C#
The latest version of C# is C# 6.0 with lots of new features, to know them read the following article:
2. What is an Object?
According to MSDN, "a class or struct definition is like a blueprint that specifies what the type can do. An
object is basically a block of memory that has been allocated and configured according to the blueprint. A
program may create many objects of the same class. Objects are also called instances, and they can be
stored in either a named variable or in an array or collection. Client code is the code that uses these
variables to call the methods and access the public properties of the object. In an object-oriented
language such as C#, a typical program consists of multiple objects interacting dynamically".
Objects helps us to access the member of a class or struct either they can be fields, methods or
properties, by using the dot. To know more about object read the following links:
OOP Overview
Unboxing:
Unboxing is also a process which is used to extract the value type from the object or any implemented
interface type. Boxing may be done implicitly, but unboxing have to be explicit by code.
Example:
The concept of boxing and unboxing underlines the C# unified view of the type system in which a value of
any type can be treated as an object.
For more details read this:
Type Conversions in C#
An abstract class can have non-abstract methods (concrete methods) while in case of interface all
the methods has to be abstract.
An abstract class can declare or use any variables while an interface is not allowed to do so.
In an abstract class all data member or functions are private by default while in interface all are
public, we cant change them manually.
In an abstract class we need to use abstract keyword to declare abstract methods while in an
interface we dont need to use that.
An abstract class cant be used for multiple inheritances while interface can be used as multiple
inheritances.
An abstract class use constructor while in an interface we dont have any type of constructor.
An enum is a value type with a set of related named constants often referred to as an enumerator list. The
enum keyword is used to declare an enumeration. It is a primitive data type, which is user defined.
An enum type can be an integer (float, int, byte, double etc.). But if you used beside int it has to be cast.
An enum is used to create numeric constants in .NET framework. All the members of enum are of enum
type. Their must be a numeric value for each enum type.
The default underlying type of the enumeration element is int. By default, the first enumerator has the
value 0, and the value of each successive enumerator is increased by 1.
1. enum Dow {Sat, Sun, Mon, Tue, Wed, Thu, Fri};
Some points about enum
Enums are not for end-user, they are meant for developers.
Enums are strongly typed constant. They are strongly typed, i.e. an enum of one type may not be
implicitly assigned to an enum of another type even though the underlying value of their members
are the same.
Enumerations (enums) make your code much more readable and understandable.
Enum values are fixed. Enum can be displayed as a string and processed as an integer.
The default type is int, and the approved types are byte, sbyte, short, ushort, uint, long, and
ulong.
Every enum type automatically derives from System.Enum and thus we can use System.Enum
methods on enums.
Enums are value types and are created on the stack and not on the heap.
1. using System;
2. using System.Collections;
3. using System.Linq;
4. using System.Text;
5.
6. namespace break_example {
7.
8.
Class brk_stmt {
9.
10.
11.
if (i == 4) {
12.
continue;
13.
14.
15.
16.
17.
18.
19.
20.
21. }
Output
The number is 0;
The number is 1;
The number is 2;
The number is 3;
Eg.Continue Statement
1. using System;
2. using System.Collections;
3. using System.Linq;
4. using System.Text;
5.
6. namespace continue_example
7. {
8.
Class cntnu_stmt
9.
10.
11.
12.
13.
14.
if (i == 4)
15.
16.
continue;
17.
18.
Console.ReadLine(The number
19.
20.
21.
22.
}
}
23.
24. }
25.
26.
Output
The number is 1;
The number is 2;
The number is 3;
The number is 5;
3.
4.
public Test() {
5.
read = 100;
6.
cons = 100;
7.
8.
9.
10.
11.
12. }
Here I was trying to change the value of both the variables in constructor but when I am trying to change
the constant it gives an error to change their value in that block which have to call at run time.
So finally remove that line of code from class and call this Check() function like the following code snippet:
1. class Program {
2.
3.
4.
obj.Check();
5.
Console.ReadLine();
6.
7. }
8. class Test {
9.
10.
11.
public Test() {
12.
read = 100;
13.
14.
15.
16.
17.
18. }
Output:
Read/Write.
ReadOnly.
WriteOnly
14. What is the difference between dispose and finalize methods in c#?
Answer: finalizer and dispose both are used for same task like to free unmanaged resources but have
some differences see.
Finalize:
Finalize used to free unmanaged resources those are not in use like files, database connections
in application domain and more, held by an object before that object is destroyed.
In the Internal process it is called by Garbage Collector and cant called manual by user code or
any service.
Implement it when you have unmanaged resources in your code, and make sure that these
resources are freed when the Garbage collection happens.
Dispose:
Dispose is also used to free unmanaged resources those are not in use like files, database
connections in Application domain at any time.
Implement this when you are writing a custom class that will be used by other users.
Note:
Performance wise string is slow because its create a new instance to override or change the
previous value.
StringBuilder:
System.Text.Stringbuilder is mutable object which also hold the string value, mutable means once we
create a System.Text.Stringbuilder object we can use this object for any operation like insert value in
existing string with insert functions also replace or append without creating new instance of
System.Text.Stringbuilder for every time so its use the previous object so its work fast as compare than
System.String. Lets have an example to understand System.Text.Stringbuilder like:
Note:
Performance wise StringBuilder is very fast because it will use same instance of StringBuilder
object to perform any operation like insert value in existing string.
Sealed classes are used to restrict the inheritance feature of object oriented programming. Once a class
is defined as a sealed class, the class cannot be inherited.
In C#, the sealed modifier is used to define a class as sealed. In Visual Basic .NET the Not Inheritable
keyword serves the purpose of sealed. If a class is derived from a sealed class then the compiler throws
an error.
If you have ever noticed, structs are sealed. You cannot derive a class from a struct.
The following class definition defines a sealed class in C#:
1. // Sealed class
2. sealed class SealedClass
3. {
4.
5. }
Boxing is the process of converting a value type data type to the object or to any interface data type which
is implemented by this value type. When the CLR boxes a value means when CLR converting a value
type to Object Type, it wraps the value inside a System.Object and stores it on the heap area in
application domain.
Example:
Unboxing:
Unboxing is also a process which is use to extracts the value type from the object or any implemented
interface type. Boxing may be done implicit but unboxing have to be explicit by code.
Example:
The concept of boxing and unboxing underlies the C# unified view of the type system in which a value of
any type can be treated as an object.
21. What is difference between late binding and early binding in c#?
Answer:
Early Binding and Late Binding concepts belongs to polymorphism so lets see first about polymorphism:
Polymorphism is an ability to take more than one form of a function means with a same name we can
write multiple functions code in a same class or any derived class.
Understanding Polymorphism in C#
Polymorphism in .NET
implement IQueryable<T>, the standard query operators cannot be used on the provider's data source.
The IQueryable interface inherits the IEnumerable interface so that if it represents a query, the results of
that query can be enumerated. Enumeration causes the expression tree associated with an IQueryable
object to be executed. The definition of "executing an expression tree" is specific to a query provider. For
example, it may involve translating the expression tree to an appropriate query language for the
underlying data source. Queries that do not return enumerable results are executed when the Execute
method is called.
IEnumerable vs IQuerable
IEnumerable Vs IQueryable
23. What happens if the inherited interfaces have conflicting method names?
Answer:
If we implement multipole interface in the same class with conflict method name so we dont need to
define all or in other words we can say if we have conflict methods in same class so we cant implement
their body independently in the same class coz of same name and same signature so we have to use
interface name before method name to remove this method confiscation lets see an example:
1. interface testInterface1 {
2.
void Show();
3. }
4. interface testInterface2 {
5.
void Show();
6. }
7. class Abc: testInterface1,
8. testInterface2 {
9.
10.
void testInterface1.Show() {
11.
12.
13.
void testInterface2.Show() {
14.
15.
16. }
Now see how to use those in a class:
1. class Program {
2.
3.
4.
5.
obj1.Show();
6.
obj2.Show();
7.
8.
9.
10. }
Console.ReadLine();
}
Output:
Overview of Arrays in C#
Doing Arrays - C#
Constructor Chaining In C#
Constructors In C#
we can use multiple Catches block with every try but when any Exceptions is throw by debugger so every
catches match this exception type with their signature and catch the exception by any single catch block
so that means we can use multiple catches blocks but only one can executed at once like:
1. using System;
2. class MyClient {
3.
4.
int x = 0;
5.
int div = 0;
6.
try {
7.
div = 100 / x;
8.
9.
10.
Console.WriteLine("DivideByZeroException");
11.
12.
Console.WriteLine("Exception");
13.
} finally {
14.
Console.WriteLine("Finally Block");
15.
16.
17.
1. Ensures a class has only one instance and provides a global point of access to it.
2. A singleton is a class that only allows a single instance of itself to be created, and usually gives
simple access to that instance.
3. Most commonly, singletons don't allow any parameters to be specified when creating the
instance, since a second request of an instance with a different parameter could be problematic!
(If the same instance should be accessed for all requests with the same parameter then the
factory pattern is more appropriate.)
4. There are various ways to implement the Singleton Pattern in C#. The following are the common
characteristics of a Singleton Pattern.
A single constructor, that is private and parameterless.
The class is sealed.
A static variable that holds a reference to the single created instance, if any.
A public static means of getting the reference to the single created instance, creating one if
necessary.
This is the example how to write the code with Singleton:
1. namespace Singleton {
2.
3.
class Program {
static void Main(string[] args) {
4.
Calculate.Instance.ValueOne = 10.5;
5.
Calculate.Instance.ValueTwo = 5.5;
6.
7.
8.
9.
10.
11.
12.
Console.WriteLine("\n----------------------\n");
13.
Calculate.Instance.ValueTwo = 10.5;
14.
15.
16.
17.
18.
19.
Console.ReadLine();
20.
21.
}
}
22.
23.
24.
private Calculate() {}
25.
26.
27.
get {
28.
if (instance == null) {
29.
30.
31.
return instance;
32.
33.
}
}
34.
35.
36.
get;
37.
set;
38.
39.
40.
get;
41.
set;
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60. }
29. Difference between Throw Exception and Throw Clause.
Answer:
The basic difference is that the Throw exception overwrites the stack trace and this makes it hard to find
the original code line number that has thrown the exception.
Throw basically retains the stack information and adds to the stack information in the exception that it is
thrown.
Let us see what it means rather speaking so many words to better understand the differences. I am using
a console application to easily test and see how the usage of the two differ in their functionality.
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5.
6. namespace TestingThrowExceptions {
7.
8.
class Program {
public void ExceptionMethod() {
9.
10.
11.
12.
13.
14.
15.
try {
16.
p.ExceptionMethod();
17.
18.
19.
throw ex;
20.
21.
22.
23. }
Now run the code by pressing the F5 key of the keyboard and see what happens. It returns an exception
and look at the stack trace:
For More Details use following link:
3.
get {
4.
5.
6.
7.
set {
8.
9.
10. }
In the above code:
<modifier>
can be private, public, protected or internal.
<return type>
can be any valid C# types.
For more details use following link:
Indexers in C#
INDEXER in C#
The return type of the delegate must be void. None of the parameters of the delegate type can be
delegate type can be declared as output parameters using out keywords.
Multicast delegate instance that created by combining two delegates, the invocation list is formed
by concatenating the invocation list of two operand of the addition operation. Delegates are
invoked in the order they are added.
8.
Console.WriteLine("Meerut");
9.
10.
11.
12.
Console.WriteLine("Roorkee");
}
13. }
14. class MTest {
15.
16.
17.
18.
MDelegate m3 = m1 + m2;
19.
MDelegate m4 = m2 + m1;
20.
MDelegate m5 = m3 - m2;
21.
m3();
22.
m4();
23.
m5();
24.
25. }
32. Difference between Equality Operator (==) and Equals() Method in C#.
Answer:
Both the == Operator and the Equals() method are used to compare two value type data items or
reference type data items. The Equality Operator (==) is the comparison operator and the Equals()
method compares the contents of a string. The == Operator compares the reference identity while the
Equals() method compares only contents. Lets see with some examples.
In this example we assigned a string variable to another variable. A string is a reference type and in the
following example, a string variable is assigned to another string variable so they are referring to the same
identity in the heap and both have the same content so you get True output for both the == Operator and
the Equals() method.
1. using System;
2. namespace ComparisionExample {
3.
class Program {
4.
5.
6.
7.
8.
9.
Console.ReadKey();
10.
11.
}
}
12. }
3.
get;
4.
set;
5.
6. }
7. class Author {
8.
9.
get;
10.
set;
11.
12. }
Now, let's try to check the preceding types as:
1. var speaker = new Speaker { Name="Gaurav Kumar Arora"};
1. var i = 4;
For more details about Nullable<> follow the link:
Example:
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5.
6. namespace Hello_Word {
7.
8.
class overloding {
public static void Main() {
9.
Console.WriteLine(volume(10));
10.
Console.WriteLine(volume(2.5F, 8));
11.
12.
Console.ReadLine();
13.
14.
15.
16.
return (x * x * x);
17.
18.
19.
20.
21.
22.
23.
24.
return (l * b * h);
25.
26.
27. }
Note:
If we have a method that have two parameter object type and have a same name method with two integer
parameter so when we call that method with int value so itll call that method have integer parameter
instead of object type parameters method.
To learn more about Method Overloading follow link:
Method Overloading in C#
will reduce the load of object creation to a great extent. This article will try to explain this in detail. The
example is for an Employee object, but you can make it general by using Object base class.
What does it mean?
Object Pool is nothing but a container of objects that are ready for use. Whenever there is a request for a
new object, the pool manager will take the request and it will be served by allocating an object from the
pool.
How it works?
We are going to use Factory pattern for this purpose. We will have a factory method, which will take care
about the creation of objects. Whenever there is a request for a new object, the factory method will look
into the object pool (we use Queue object). If there is any object available within the allowed limit, it will
return the object (value object), otherwise a new object will be created and give you back.
For more Details follow the link:
Generic classes and methods combine reusability, type safety and efficiency in a way that their nongeneric counterparts cannot. Generics are most frequently used with collections and the methods that
operate on them. Version 2.0 of the .NET Framework class library provides a new namespace,
System.Collections.Generic, that contains several new generic-based collection classes. It is
recommended that all applications that target the .NET Framework 2.0 and later use the new generic
collection classes instead of the older non-generic counterparts such as ArrayList.
Features of Generics
Generics is a technique that enriches your programs in the following ways:
You can create generic collection classes. The .NET Framework class library contains several
new generic collection classes in the System.Collections.Generic namespace. You may use these
generic collection classes instead of the collection classes in the System.Collections namespace.
You can create your own generic interfaces, classes, methods, events and delegates.
You may create generic classes constrained to enable access to methods on specific data types.
You may get information on the types used in a generic data type at run-time using reflection.
Introduction to Generics in C#
Generics in C#
A virtual method is a method that can be redefined in derived classes. A virtual method has an
implementation in a base class as well as derived the class. It is used when a method's basic functionality
is the same but sometimes more functionality is needed in the derived class. A virtual method is created
in the base class that can be overridden in the derived class. We create a virtual method in the base class
using the virtual keyword and that method is overridden in the derived class using the override keyword.
When a method is declared as a virtual method in a base class then that method can be defined in a base
class and it is optional for the derived class to override that method. The overriding method also provides
more than one form for a method. Hence it is also an example for polymorphism.
When a method is declared as a virtual method in a base class and that method has the same definition
in a derived class then there is no need to override it in the derived class. But when a virtual method has a
different definition in the base class and the derived class then there is a need to override it in the derived
class.
When a virtual method is invoked, the run-time type of the object is checked for an overriding member.
The overriding member in the most derived class is called, which might be the original member, if no
derived class has overridden the member.
Virtual Method
1. By default, methods are non-virtual. We can't override a non-virtual method.
2. We can't use the virtual modifier with the static, abstract, private or override modifiers.
For More Details follow the link:
Virtual Method in C#
40. What are the Difference between Array and ArrayList in C#.Net?
Answer:
Difference between Array and ArrayList
41. What you understand by Value types and Reference types in C#.Net?
Answer:
In C# data types can be of two types: Value Types and Reference Types. Value type variables contain
their object (or data) directly. If we copy one value type variable to another then we are actually making a
copy of the object for the second variable. Both of them will independently operate on their values, Value
Type member will located into Stack and reference member will located in Heap always.
Let consider each case briefly.
1. Pure Value Type
Here I used a structure as a value type. It has an integer member. I created two instances of this
structure. After wards I assigned second instance to the first one. Then I changed the state of
second instance, but it hasn't effect the first one, as whole items are value type and assignments
on those types will copy only values not references i.e. in a Value Type assignment, all instances
have its own local copy of members.
2. Soap Serialization (Save your object data into binary format; mainly used in network related
communication).
3. XmlSerialization (Save your object data into an XML file).
For more details follow the link:
Use of Serialization in C#
Serializing Objects in C#
A single-threaded process contains only one thread while a multithreaded process contains more than
one thread for execution.
System.Threading Namespace
Like many other features, in .NET, System.Threading is the namespace that provides various types to
help in construction of multithreaded applications.
ForeName = "Jignesh",
4.
SurName = "Trivedi"
5. };
3.
get;
4.
set;
5.
6.
7.
get;
8.
set;
9.
10.
11.
get;
12.
set;
13.
14.
15.
get;
16.
set;
17.
18. }
19. static void Main(string[] args) {
20.
21.
List < MyData > data = new List < MyData > ();
22.
data.Add(new MyData {
23.
24.
});
25.
data.Add(new MyData {
26.
27.
});
28.
data.Add(new MyData {
29.
30.
});
31.
data.Add(new MyData {
32.
15)
33.
});
34.
data.Add(new MyData {
35.
36.
37. }
});
pl.FirstName, pl.LastName
41. };
42. foreach(var m in anonymousData) {
43.
44. }
45. }
47. Explain Hashtable in C#?
Answer:
A Hashtable is a collection that stores (Keys, Values) pairs. Here, the Keys are used to find the storage
location and is immutable and cannot have duplicate entries in the Hashtable. The .Net Framework has
provided a Hash Table class that contains all the functionality required to implement a hash table without
any additional development. The hash table is a general-purpose dictionary collection. Each item within
the collection is a DictionaryEntry object with two properties: a key object and a value object. These are
known as Key/Value. When items are added to a hash table, a hash code is generated automatically. This
code is hidden from the developer. All access to the table's values is achieved using the key object for
identification. As the items in the collection are sorted according to the hidden hash code, the items
should be considered to be randomly ordered.
The Hashtable Collection
The Base Class libraries offers a Hashtable Class that is defined in the System.Collections namespace,
so you don't have to code your own hash tables. It processes each key of the hash that you add every
time and then uses the hash code to look up the element very quickly. The capacity of a hash table is the
number of elements the hash table can hold. As elements are added to a hash table, the capacity is
automatically increased as required through reallocation. It is an older .Net Framework type.
Declaring a Hashtable
The Hashtable class is generally found in the namespace called System.Collections. So to execute any of
the examples, we have to add using System.Collections; to the source code. The declaration for the
Hashtable is:
1. Hashtable HT = new Hashtable ();
3. It allows you to query collections like arrays, enumerable classes etc in the native language of
your application, like VB or C# in much the same way as you would query a database using SQL.
File handling in C#
Reflection typically is used to dump out the loaded assemblies list, their reference to inspect methods,
properties etcetera. Reflection is also used in the external disassembling tools such Reflector, Fxcop and
NUnit because .NET tools don't need to parse the source code similar to C++.
Metadata Investigation
The following program depicts the process of reflection by creating a console based application. This
program will display the details of the fields, methods, properties and interfaces for any type within the
mscorlib.dll assembly. Before proceeeding, it is mandatory to import "System.Reflection".
Here, we are defining a number of static methods in the program class to enumerate fields, methods and
interfaces in the specified type. The static method takes a single "System.Type" parameter and returns
void.
1. static void FieldInvestigation(Type t) {
2.
Console.WriteLine("*********Fields*********");
3.
4.
foreach(FieldInfo f in fld) {
5.
6.
Console.WriteLine("-->{0}", f.Name);
}
7. }
8.
9. static void MethodInvestigation(Type t) {
10.
Console.WriteLine("*********Methods*********");
11.
12.
foreach(MethodInfo m in mth) {
13.
14.
15. }
Console.WriteLine("-->{0}", m.Name);
}