1) What Is C-Sharp (C#) ?
1) What Is C-Sharp (C#) ?
C# is a type-safe, managed and object oriented language, which is compiled by .Net framework
for generating intermediate language (IL).
Easy to learn
Object oriented
Component oriented
Part of .NET framework
class X {}
sealed class Y : X {}
Sealed methods –
class A
{
protected virtual void First() { }
protected virtual void Second() { }
}
class B : A
{
sealed protected override void First() {}
protected override void Second() { }
}
If any class inherits from class “B” then method – “First” will not be overridable as this method
is sealed in class B.
Array stores the values or elements of same data type but arraylist stores values of
different datatypes.
Arrays will use the fixed length but arraylist does not uses fixed length like array.
“Using” statement calls – “dispose” method internally, whenever any exception occurred in any
method call and in “Using” statement objects are read only and cannot be reassignable or
modifiable.
Namespaces are containers for the classes. We will use namespaces for grouping the related
classes in C#. “Using” keyword can be used for using the namespace in other namespace.
12) What is the difference between “constant” and “readonly” variables in C#?
“Const” keyword is used for making an entity constant. We cannot modify the value later
in the code. Value assigning is mandatory to constant variables.
“readonly” variable value can be changed during runtime and value to readonly variables
can be assigned in the constructor or at the time of declaration.
“Static” keyword can be used for declaring a static member. If the class is made static then all
the members of the class are also made static. If the variable is made static then it will have a
single instance and the value change is updated in this instance.
14) What is the difference between “dispose” and “finalize” variables in C#?
Dispose - This method uses interface – “IDisposable” interface and it will free up both
managed and unmanaged codes like – database connection, files etc.
Finalize - This method is called internally unlike Dispose method which is called
explicitly. It is called by garbage collector and can’t be called from the code.
No. Once any exception is occurred it executes specific exception catch block and the control
comes out.
“Finally” block will be executed irrespective of exception. So while executing the code in try
block when exception is occurred, control is returned to catch block and at last “finally” block
will be executed. So closing connection to database / releasing the file handlers can be kept in
“finally” block.
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.
“throw” will preserve the original stack trace info.
20) Can we have only “try” block without “catch” block in C#?
23) Mention the assembly name where System namespace lies in C#?
24) What are the differences between static, public and void in C#?
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.
26) Explain Jagged Arrays in C#?
If the elements of an array is an array then it’s called as jagged array. The elements can be of
different sizes and dimensions.
decimal
int
byte
enum
double
long
float
class
string
interface
object
No. We can’t override private virtual methods as it is not accessible outside the class.
“protected internal” can be accessed in the same assembly and the child classes can also access
these methods.
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.
“CopyTo()” method can be used to copy the elements of one array to other.
“Clone()” method is used to create a new array to contain all the elements which are in
the original array.
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.
This is a situation where in, multiple resources are dependent on each other and this causes a
lock condition and this makes the resource to be unused.
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.
Object pool is used to track the objects which are being used in the code. So object pool reduces
the object creation overhead.
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.
Single Delegate
Multicast Delegate
Generic Delegate
Function
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
Abstract and Encapsulate method
Multicasting
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,
50) What is the difference between “as” and “is” operators in C#?
A delegate with multiple handlers are called as multicast delegate. The example to demonstrate
the same is given below
public delegate void CalculateMyNumbers(int x, int y);
int x = 6;
int y = 7;
CalculateMyNumbers addMyNumbers = new
CalculateMyNumbers(FuncForAddingNumbers);
CalculateMyNumbers multiplyMyNumbers = new
CalculateMyNumbers(FuncForMultiplyingNumbers);
CalculateMyNumbers multiCast = (CalculateMyNumbers)Delegate.Combine
(addMyNumbers, multiplyMyNumbers);
multiCast.Invoke(a,b);
C# code is managed code because the compiler – CLR will compile the code to Intermediate
Language.
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.
It is used to store the key/value pairs based on hash code of the key. Key will be used to access
the element in the collection. For example,
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");
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#?
Using System.IO;
File.WriteAllText(”mytextfilePath”, “MyTestContent”);
Boxing – This is the process of converting from value type to reference type. For example,
int myvar = 10;
object myObj = myvar;
UnBoxing – It’s completely opposite to boxing. It’s the process of converting reference type to
value type. For example,
int myvar2 = (int)myObj;
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.
C# Compiler is – CSC.
If the constructor contains the same class in the constructor parameter then it is called as copy
constructor.
class MyClass
{
public string prop1, prop2;
public MyClass(string a, string b)
{
prop1 = a;
prop2 = b;
}
If the constructor is declared as static then it will be invoked only once for all number of
instances of a class. Static constructor will initialize the static fields of a class.
class MyClass
{
public string prop1, prop2;
public MyClass(string a, string b)
{
prop1 = a;
prop2 = b;
}
Static MyClass()
{
Console.WriteLine(“Static Constr Test”);
}
public MyClass(MyClass myobj) // Copy Constructor
{
prop1 = myobj.prop1;
prop2 = myobj.prop2;
}
}
68) Which string method is used for concatenation of two strings in c#?
“Concat” method of String class is used to concatenate two strings. For example,
string.Concat(firstStr, secStr)
Indexers are used for allowing the classes to be indexed like arrays. Indexers will resemble the
property structure but only difference is indexer’s accessors will take parameters. For example,
class MyCollection<T>
{
private T[] myArr = new T[100];
public T this[int t]
{
get
{
return myArr[t];
}
set
{
myArr[t] = value;
}
}
}
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.
Conditional
Obsolete
Attribute Usage
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 it’s better to use
Multithreading., which involves multiple threads.
Unstarted State
Ready State
Not Runnable State
Dead State
CurrentCulture
CurrentThread
CurrentContext
IsAlive
IsThreadPoolThread
IsBackground
Priority
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 – 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.
Protected Internal – If an attribute or method is defined as Protected Internal, access is
restricted to classes within the current project assembly and types derived from the
containing class.
If an attribute's value had to be same across all the instances of the same class, the static keyword
is used. For example, if the Minimum salary should be set for all employees in the employee
class, use the following code.
To access a private or public attribute or method in a class, at first an object of the class should
be created. Then by using the object instance of that class, attributes or methods can be accessed.
To access a static variable, we don't want to create an instance of the class containing the static
variable. We can directly refer that static variable as shown below.
Let us explain this with the help of an example. In the code given below,
Employee emp1;
Employee emp2 = new Employee();
emp1 = emp2;
Here emp2 has an object instance of Employee Class. But emp1 object is set as emp2. What this
means is that the object emp2 is referred in emp1, rather than copying emp2 instance into emp1.
When a change is made in emp2 object, corresponding changes can be seen in emp1 object.
Properties are a type of class member, that are exposed to the outside world as a pair of Methods.
For example, for the static field Minsalary, we will Create a property as shown below.
set Method will get triggered and value will be stored in minimumSalary field.
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);
Constructor overloading
Function overloading
Operator overloading
In Constructor overloading, n number of constructors can be created for the same class. But the
signatures of each constructor should vary. For example
In Function overloading, n number of functions can be created for the same class. But the
signatures of each function should vary. For example
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;
public Rectangle(int w,int h)
{
Width=w;
Height=h;
}
public static bool operator >(Rectangle a,Rectangle b)
{
return a.Height > b.Height ;
}
public static bool operator <(Rectangle a,Rectangle b)
{
return a.Height < b.Height ;
}
}
Let us call the operator overloaded functions from the method given below. When first if
condition is triggered, the first overloaded function in the rectangle class will be triggered. When
second if condition is triggered, the second overloaded function in the rectangle class will be
triggered.
Data Encapsulation is defined as the process of hiding the important fields from the end user. 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. This is inline with the OOPS Concept that an external user should know
about the what an object does. How it does it, should be decided by the program. 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;
}
}
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.
In C#, derived classes can inherit from one base class only. If you want to inherit from multiple
base classes, use interface.
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
When we want to give permission to a derived class to override a method in base class, Virtual
keyword is used. For example. lets us look at the classes Car and Ford as shown below.
class Car
{
public Car()
{
Console.WriteLine("Base Class Car");
}
public virtual void DriveType()
{
Console.WriteLine("Right Hand Drive");
}
}
To override a base class method which is defined as virtual, Override keyword is used. In the
above example, method DriveType is overridden in the derived class.
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.
public Car()
{
Console.WriteLine("Base Class Car");
}
When ever an instance of class car is created from the same class or its derived class(Except Few
Scenarios), Constructor get called and sequence of code written in the constructor get executed.
interface Breaks
{
void BreakType();
}
interface Wheels
{
void WheelType();
}