Professional Documents
Culture Documents
C#new
C#new
C#new
Garbage collection is a CLR feature which automatically manages memory. CLR automatically releases
objects when they are no longer used and referenced. Following methods are used for garbage
collection –
GC.Collect()
Dispose()
Finalize()
CLR is .NET equivalent of Java Virtual Machine (JVM). It is the runtime that converts a MSIL
code into the host machine language code, which is then executed appropriately. The CLR is the
execution engine for .NET Framework applications. It provides a number of services, including:
- Code management (loading and execution)
- Application memory isolation
- Verification of type safety
- Conversion of IL to native code.
- Access to metadata (enhanced type information)
- Managing memory for managed objects
- Enforcement of code access security
- Exception handling, including cross-language exceptions
- Interoperation between managed code, COM objects, and pre-existing DLL's (unmanaged code
and data)
- Automation of object layout
- Support for developer services (profiling, debugging, and so on).
CTS defines all of the basic types that can be used in the .NET Framework and the operations
performed on those type. All this time we have been talking about language interoperability, and
.NET Class Framework. None of this is possible without all the language sharing the same data
types. What this means is that an int should mean the same in VB, VC++, C# and all other .NET
compliant languages. This is achieved through introduction of Common Type System (CTS).
CLS is the collection of the rules and constraints that every language (that seeks to achieve .NET
compatibility) must follow. It is a subsection of CTS and it specifies how it shares and extends
one another libraries.
CLR and DLR?
A. CLR (Common Language Runtime) is the utility in the .Net framework to run the
application. It is the run-time engine which actually executes the application with
many responsibilities like taking care of memory management, versioning, CasPol
etc.
DLR is new with .Net 4.0 which is the Dynamic Language Runtime and used to run
the application on the fly wherever required. CLR runs as statically while DLR runs
dynamically.
Read-only: The value will be initialized only once from the constructor of the class.
Static: Value can be initialized once.
Ans: Static is same as constant variable but we can change the value of static variable and
we can access the variables without creating any instances
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.
private static double MinSalary = 30000;
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.
double var = Employee.MinSalary ;
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.
Don't Miss - Database Interview Questions and Answers
“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.
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;
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;
Ans: The basic difference between them is “Convert” function handles NULLS while
“.ToString()” does not it will throw a NULL reference exception error. So as a good coding
practice using “convert” is always safe.
String objects are immutable as its state cannot be modified once created. Every time when
we perform any operation like add, copy, replace, and case conversion or when we pass a
string object as a parameter to a method a new object will be created.
Example:
String str = "ABC";
str.Replace("A","X");
Here Replace() method will not change data that "str" contains, instead a new string object
is created to hold data "XBC" and the reference to this object is returned by
Replace() method.
“Concat” method of String class is used to concatenate two strings. For example,
string.Concat(firstStr, secStr)
Explain Inheritance in C# ?
When a class (type) is derived from another class(type) such that it inherits all the members of
the base type it is Implementation Inheritance.
When a type (class or a struct) inherits only the signatures of the functions from another type it is
Interface Inheritance.
In general Classes can be derived from another class, hence support Implementation inheritance.
At the same time Classes can also be derived from one or more interfaces. Hence they support
Interface inheritance.
The class which derives functionality from a base class is called a derived class. A derived class
can also act as a base class for another class. Thus it is possible to create a tree-like structure that
illustrates the relationship between all related classes. This structure is known as the inheritance
hierarchy.
.NET supports only single inheritance. However the purpose is accomplished using multiple
interfaces.
In C#, derived classes can inherit from one base class only. If you want to inherit from multiple base
classes, use interface.
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
Compile time polymorphism. Best example is Overloading
Runtime polymorphism. Best example is Overriding
Explain Overloading in C# ?
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
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.
public static void Main()
{
Rectangle obj1 =new Rectangle();
Rectangle obj2 =new Rectangle();
if(obj1 > obj2)
{
Console.WriteLine("Rectangle1 is greater than Rectangle2");
}
if(obj1 < obj2)
{
Console.WriteLine("Rectangle1 is less than Rectangle2");
}
}
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)
{}
}
What is a Constructor in C# ?
Constructor is a special method that get invoked/called automatically, whenever an object of a given
class gets instantiated. In our class car, constructor is defined as shown below
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();
}
class Ford : Breaks, Wheels
{
public Ford()
{
Console.WriteLine("Derived Class Ford");
}
public void Price()
{
Console.WriteLine("Ford Price : 100K $");
}
public void BreakType()
{
Console.WriteLine("Power Break");
}
public void WheelType()
{
Console.WriteLine("Bridgestone");
}
}
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;
}
}
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;
}
public MyClass(MyClass myobj) // Copy Constructor
{
prop1 = myobj.prop1;
prop2 = myobj.prop2;
}
}
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)
{}
}
Define Overriding?
Overriding is a concept where a method in a derived class uses the same name, return type, and
arguments as a method in its base class. In other words, if the derived class contains its own
implementation of the method rather than using the method in the base class, the process is
called overriding.
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");
}
}
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
Right Hand Drive
Base Class Car
Derived Class Ford
Right Hand
If the derived class doesn't want to use methods in the base class, derived class can implement it's own
version of the same method with same signature. For example, in the classes given below, DriveType() is
implemented in the derived class with same signature. This is called Method Hiding.
class Car
{
public void DriveType()
{
Console.WriteLine("Right Hand Drive");
}
}
class Ford : Car
{
public void DriveType()
{
Console.WriteLine("Right Hand ");
}
}
“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.
Ans: Two types of memories are there in .net stack memory and heap memory
What are the differences between value type and reference type?
Ans: Value type contain variable and reference type are not containing value directly in its
memory.
Memory is allocated in managed heap in reference type and in value type memory allocated
in stack. Reference type ex-class value type-struct, enumeration
A. Value type holds data directly, Value type stored in the stack memory, we can
get the direct value of the value types. Value type data type can’t be null.
Reference types: This type doesn’t hold the data directly. They hold the address on
which the actual data present. They stored in heap memory, Can have default
values.
We can make and work with null reference type.
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.
Explain circular reference in C#?
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.
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 ");
}
}
If we don't want a class to be instantiated, define the class as abstract. An abstract class can have
abstract and non abstract classes. If a method is defined as abstract, it must be implemented in derived
class. For example, in the classes given below, method DriveType is defined as abstract.
abstract 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.
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.
Abstract Class:
-Abstract class provides a set of rules to implement next class
-Rules will be provided through abstract methods
-Abstract method does not contain any definition
-While inheriting abstract class all abstract methods must be override
-If a class contains at least one abstract method then it must be declared as an “Abstract
Class”
-Abstract classes cannot be instantiated (i.e. we cannot create objects), but a reference can
be created
-Reference depends on child class object’s memory
-Abstract classes are also called as “Partial abstract classes”
-Partial abstract class may contain functions with body and functions without body
-If a class contains all functions without body then it is called as “Fully Abstract Class”
(Interface)
Interface:
-If a class contains all abstract methods then that class is known as “Interface”
-Interfaces support like multiple inheritance
-In interface all methods r public abstract by default
-Interfaces r implementable
-Interfaces can be instantiated, but a reference cannot be created
Ans: When we want that sub class must implement all the methods of base class. In such a
situation we will implement the interface. In the other hand when we want only some
method of base class in our sub class then use base class as abstract class.
Difference between Abstract classes and Interface. Explain with scenario where to
implement one?
A. Collection of the Abstract (Incomplete) and Concrete (complete) methods is
called as the Abstract class. If there is at least one abstract method in a class, the
class must be abstract class.
When there is the similar behavior, we can use the abstract class.
e.g. We want to calculate the area of few component. As this is not generic to the
application. We have only few component- like Circle, Ellipse, parabola, Hyperbola,
Triangle etc.
So we can create an abstract class and implement it like below:
public abstract class MyAbstractClass
{
// some other concrete members
public abstract void Area();// abstract member
}
Now in the child class, let’s say i have a circle class and want to calculate the area
of the circle:
public class Cicle: MyAbstractClass
{
public override void Area()
{
// calculate the area of the circle
}
}
In the similar fashion, we can calcite the area of other shapes.
Collection of abstract members is called as the Interface. When the behavior is not
similar, we need to use the interface. All the members of the interface
must be overrides in the child class.
e.g. Print functionality of the application can have an interface like:
interface Inf
{
void Print();
}
Now as this is the generic functionality and can be implemented in any of the page
so we have taken it as interface. Now we can implement this functionality in to any
page like:
class MyClass:Inf
{
public void print
{
// write details about the print
}
// Here we can implement any kind of print-like print to excel, xml, word all depends on the
our decision.
}
Different Access Modifier are - Public, Private, Protected, Internal, Protected Internal
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.
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.
private double minimumSalary;
public static double MinSalary
{
get
{
return minimumSalary;
}
set
{
minimumSalary = value;
}
}
So when we execute the following lines code
double minSal = Employee.MinSalary;
get Method will get triggered and value in minimumSalary field will be returned. When we execute,
Employee. MinSalary = 3000;
set Method will get triggered and value will be stored in minimumSalary field.
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 can’t be inherited. Below is the sample code
of using Enums
Eg: enum Fruits { Apple, Orange, Banana, WaterMelon};
Exception handling.
A. Exception Handling is the way to handle the unexpected error. From the SQL
Server 2005 version, try…catch block is also supported to catch the exceptions in
SQL Server database. There is various other ways to catch the error like @@Error
which is the global variable and used to get the error. RaiseError is another inbuilt
method which is used to display the error.
Ans: The difference between application exception and system exception is that system
exceptions are thrown by CLR and application exceptions are thrown by applications.
If I write System.exit (0); at the end of the try block, will the finally block still
execute?
Ans: No in this case the finally block will not execute because when you say
system.exit(0),the control immediately goes out of the program, and thus finally never
executes.
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.
Inner exception is a property of exception class which will give you a brief insight of the exception i.e,
parent exception and child exception details.
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.
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);
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”};
Ans: Instead of defining an entire class, you can split the definition into multiple classes by
using partial class keyword. When the application compiled, c# compiler will group all the
partial classes together and treat them as a single class. There are a couple of good reasons
to use partial classes. Programmers can work on different parts of classes without needing
to share same physical file
Ex:
Public partial class employee
{
Public void somefunction()
{
}
}
Public partial class employee
{
Public void function ()
{
}
}
GAC (Global Assembly Cache) is used to share .NET assemblies. GAC will be used in the below scenarios
–
If the multiple application wanted to use the same assembly.
If the assembly has security requirements. For example, if only administrators have the permission to
remove the assembly
What are Assemblies and Namespaces and explain the difference between them ?
Namespaces are the containers for holding the classes. In Object Oriented world, it is possible that
programmers will use the same class name. By using namespace along with class name this collision can
be removed.
An assembly exists as a .DLL or .EXE that contains MSIL code that is executed by CLR.
An assembly contains interface and classes and it can also contain other resources like files, bitmaps etc.
What is globalization?
Globalization is the process of customizing applications that support multiple cultures and
regions.
What is localization?
Localization is the process of customizing applications that support a given culture and regions.
What is Collation?
Ans: Collation refers to a set of rules that determine how the data is sorted and compared.
“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.
Explain Hashtable in C#?
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,
Hashtable myHashtbl = new Hashtable(); myHashtbl.Add("1", "TestValue1");
myHashtbl.Add("2", "TestValue2");
Method – “ContainsKey” can be used to check the key in hash table. Below is the sample code for the
same –
Eg: myHashtbl.ContainsKey("1");
Ans: 1) Hash table store data as name, value pair. While in array only value is store.
2) To access value from hash table, you need to pass name. While in array, to access value,
you need to pass index number.
3) you can store different type of data in hash table, say int, string etc. while in array you
can store only similar type of data.
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.
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.
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.
“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
What is Strong Name?
A. Strong Name (SN) is used to make the dll as the unique as:
SN -k fileName.dll
Now it will have the unique name. This assembly when placed in the GAC, it will
treat as the unique with its version number and other details. 2 assemblies with the
same name can exist in the GAC but both will have different version. The CLR takes
the latest version assembly while running the application