You are on page 1of 36

1

Question 1: So what makes your code really object-oriented?
In order to understand this, we must first analyze what benefits we can derive from OO. In order to do this, we
must clearly understand its foundation.
So given that C# is at its core object-oriented, most interviewers might be tempted to ask the following
question:
Question 2: What are the fundamental principles of OO programming?
As a developer, you might be tempted to answer that it comprises things like Encapsulation, Polymorphism,
Abstraction, and Inheritance. Although this is true, it doesn’t really explain the fundamental core of what OO is
and what its benefits are.
Principles are crucial but they are not the most important aspect of what OO actually is. What is really important
is to understand in what grounds OO is built upon, or in other words, what are the foundations of OO
programming.
The two most fundamental core concepts on which OO has been built upon in C# are this pointer and Dynamic
Dispatch.
Obviously, there are principles like Encapsulation, Polymorphism, Abstraction, and Inheritance, but these are the
consequence and not the generating force behind the OO paradigm in C#.
Question 3: What is the this Pointer?
The this pointer is silently passed with a call to an instance-level function, which then operates on an object
(instance of a class).
Basically, this core mechanism makes it possible to bring operations close to data. It also eliminates the need to
have global functions and it gives data structures the intrinsic ability to perform operations on its data.
So, having said this, if we now raise the following question:
Question 4: What is the OO fundamental idea using C# that allows a data structure to perform
operations on its own data?
What would your answer be? Pretty obvious. The humble this pointer.
Notice that despite this being a mind-bending idea, we can already start to appreciate the bigger picture for
which C# was designed.
The this pointer is basically a way for a data structure (object) to be able to access methods that allow itself to
perform operations on its own data. It is a way to manage state within a data structure.
Now let’s talk a bit about the other core concept that takes this to the next level.
Question 5: What is Dynamic Dispatch?
Dynamic Dispatch becomes possible when each object carries data about its generating type, which is basically
the object’s duty.
It is possible to achieve this when the type is able to keep track by using a virtual functions table, becoming the
type’s duty. This allows an object to override some functions which have been inherited from its base type.
The bottom line is that when we place a call to a function, we don’t really know in an OO paradigm which
function is really going to be executed.
In fact, it is the runtime’s duty to jump in when a call is placed on an object and determine which concrete
function address to invoke, by looking at its generating type.
This constitutes the base of Polymorphism. If this sounds a bit intimidating, it will become clearer with an
example going forward.
OO as a Mindset
One key aspect to understand is that it is possible to write OO code in a structured language like C, although the
language itself was not designed with that paradigm in mind.
So it is not really the programming language that is object-oriented, but it’s more how we interact with it—how
we use it.
It is true though those languages that are built from the ground up with OO fundamental core concepts and
principles such as C#, make it easier for developers to implement code that is OO compliant, however, it is still
largely known that many developers still use the language like they would use a procedural and structured
language.
At the end of the day, OO is a shift in the thinking process on how developers write software. Some
programming languages are better suited for this paradigm than others and C# is one of them.
Starting to think OO
So if C# is a language designed to be OO from the ground up—
Question 6: Why do we still see so much non-OO code written in C# today?
The problem basically resides in the fact that it takes a deep understanding of OO in order to actually start
writing code that behaves that way.
In order to really start thinking about how to properly implement OO code, it is critically important to know what
data goes together with which operations—this consists of defining objects, their data, and operations.
Also, it is important to recognize which operations requests are dispatched dynamically—this consists of applying
virtual functions and method overrides by means of inheritance, which leads to Polymorphism.
At this point, everything else pretty much comes as a byproduct of the other two core concept just mentioned:
defining data and operations together and recognizing which operations are dynamically dispatched.
These lead to objects being brought to life. This allows operations to be determined dynamically and behavior
modified by substituting objects.
So in short, the this pointer which is part of every instance and dynamic dispatching, which makes it possible to
substitute one function specification with another during runtime—without affecting the caller, are at the core of
OO.
The rest of the known OO principles such as Inheritance and Abstract Types are simply syntactical sugar on top
of these two fundamental concepts.
Question 7: How does OO simplify development?

2

The goal of any software is to be useful to its users. If you’ve been long enough in the software industry you
know how much customer requirements can change throughout time and with every one of those changes, the
code needs to be modified and re-checked.
This process can be a complicated endeavor depending on the scope of the requirements and changes
associated with them.
Let’s take for instance the following example. The program below reverses a string. This was the initial user
requirement. So given this requirement, one might be tempted to write this in C# using Visual Studio 2015 as
follows.
Example Problem 1:
using System;

namespace TestApp
{
class Program
{
public static string ReverseString(string s)
{
string tmp = string.Empty;

for (int i = s.Length - 1; i >= 0; i--)
{
tmp += s[i].ToString();
}

return tmp;
}

static void Main(string[] args)
{
Console.WriteLine(ReverseString("Pizza"));
Console.Read();
}
}
}
\

Cool! That works. We’ve solved the user’s requirements in a simple way. However what happens if the
requirements suddenly change and we are asked to filter out characters that are not letter or digits.
Easy right? We can solve this by simply adding a condition that evaluates if a character within the string is
either a digit or a letter and if that is true, then the character can be appended to the temporary string that is
returned by the function. Let’s have a look.
using System;

namespace TestApp
{
class Program
{
public static string ReverseString(string s)
{
string tmp = string.Empty;

for (int i = s.Length - 1; i >= 0; i--)
{
if (char.IsLetterOrDigit(s[i]))
tmp += s[i].ToString();
}

return tmp;
}

static void Main(string[] args)
{
Console.WriteLine(ReverseString("P!zza"));
Console.Read();
}

3

}
}
If we execute this code with the string P!zza, we get the following result.

Awesome, that also works. So that was easy to get resolved. But what happens if user requirements change
again and they become a bit more complex. Say for instance that P1zza would be a valid string to reverse, but
not P2zza or P3zza.
Although this is a hypothetical example, in real life user requirements are prone to change and this has a direct
impact on the code we write.
At the moment, we are simply using C# to write procedural code. The class is simply a wrapper around the
procedural code and nothing more.
We are not really doing any OO programming and definitely not using the full potential of C#.
Question 8: So how can we use the core concepts of OO in order to make this code easy to maintain
and yet still flexible enough to cope with possibly ever-changing requirements?
In order to answer this question properly, we first need to understand what the problem is.
Basically, the issue with the way the current code has been written is that the decision of which characters
should be reversed is static. The solution to the problem is to make that decision dynamically.
The static code runs into a fundamental problem every time a change needs to be done. That fundamental issue
is that each change may break a feature that used to work fine. This is definitely not what any developer wants.
So in order to make the code less static, let’s consider this. What if we rewrite the code with a selector that is
responsible for returning the characters that can be reversed?
Let’s have a look how this can be done.
Example Problem 2:
using System;

namespace TestApp
{
class Program
{
public static string ReverseString(string s, Selector sl)
{
string tmp = string.Empty;

foreach (char c in sl.pick(s))
{
tmp += s[i].ToString();
}

return tmp;
}

static void Main(string[] args)
{
Console.WriteLine(ReverseString("P!zza"));
Console.Read();
}
}
}
In this example, we’ve removed the responsibility of determining which character in the string could be reversed
from the ReverseString function to a Pick method available within a Selector instance that is passed to the
calling function.
That’s definitely a step in the right direction as the responsibility should be contained within a class and not let
the calling function (in this case ReverseString) to have to decide which characters to use.
Question 9: How to avoid the NULL trap?
In real life, null is nothing. However, in the programming world, null does represent the value of nothing.
Basically, nothing is a value!
Still today, we see lots of code out there that contains many conditional statements that check if the value of a
variable is null. This is a cause for concern in OO programming and here’s why.
Null is not an object. We might have a class, but when we have a variable with a null value we don’t have an
object. Simply put, we cannot build OO code based on null references!
Therefore we need to avoid the null trap. Let’s examine the following code.
Example Problem 3:
using System;

namespace TestApp
{
class Program
{
public static string DisplayUpperStr(string s)
{
string upper = string.Empty;

So you might be asking yourself at this moment: Question 11: What is a state-related codebase? Well.WriteLine(DisplayUpperStr("to upper")). Furthermore. Example Problem 4: using System. So in light of that. Even though this works fine. Despite not having an implementation for a PossibleString class yet.Read(). return upper. this code is perfectly fine and it produces the desired result. Console. 4 if (s == null) { upper = null. less cluttered and it no longer uses a conditional statement to check for a null value. } return upper. } static void Main(string[] args) { Console. } else { upper = s. } } } Syntactically. let’s move to a state-related code base. Let’s consider the following code. which is to convert to upper case a given string. the responsibility of converting the string to the upper case has moved from the calling function to the PossibleString object.Read(). Question 10: How to move to a State-related Codebase? So now that we’ve explored these concepts. the DisplayUpperStr function became more readable. Console. namespace TestApp { class Program { public static string DisplayUpperStr(PossibleString s) { string upper = s. So.ToPossiblyUpper(). return upper.WriteLine(DisplayUpperStr("to upper")). Much cleaner and easier to maintain. it is advisable from an OO perspective to consider constructing an object that represents nothing. } static void Main(string[] args) { Console. we can already start to appreciate the benefit that the OO paradigm provides in this example. first things first and let’s start by turning conditions into functions. rather than evaluating a condition that contains a null. it is a way to write code that basically replaces branching and conditional statements with functions and then some of those functions can be used to manage state within a class. } } } Notice how all of a sudden. .ToUpper().ToPossiblyUpper(). This leads to a separation of concerns in the code. specifically by invoking its method ToPossiblyUpper. which eventually leads to Encapsulation. using System. namespace TestApp { class Program { public static string DisplayUpperStr(PossibleString s) { string upper = s. let’s modify the previous code as follows.

Now let’s take this a notch further and see how we can turn a function into a state. namespace TestApp { public class Taxi { public void Pay() { this. and Abstraction. } } } This basically removes the condition from being the responsibility of the Pay method and delegates it to the ManageBooking method. PayToDriver(). By being an Action. namespace TestApp { public class Taxi { public void Pay() { this. Also. Overall. So considering this. Wrapping This Up OO is a great programming paradigm and as a developer. . using System. } } } Notice that ManageBooking is no longer a method but instead an Action. delegate which is then fully responsible for handling state. what is required is to have this responsibility detached from the Pay method and have it as an Action that handles the booked state. is a great way to make yourself noticeable to any recruiting party and help you shine during an interview. Notice that it should be an Action delegate. then no payment takes place (the PayToDriver method is not executed). greatly improves the chances of being able to adapt faster to an environment of continuous user requirement changes.WriteLine(DisplayUpperStr("to upper")). you should now try to envision and create the implementation for the ManageBooking action. Notice how these small but crucial changes have been key in simplifying the code. being able to demonstrate how agility can be put forth as code. there is a Pay method that has a guard clause. Encapsulation. Pay is still responsible for checking if a taxi has been booked. knowing how the core concepts of C# in relation to OO can help in writing software that has a clear separation of concerns. Therefore. however. Inheritance.StayVerified. 5 } static void Main(string[] args) { Console. So something like this: using System. As an exercise. The taxi company doesn’t pick up any passenger from the street. moving responsibility away from the calling class to the actual object that should ultimately be responsible for it.ManageBooking(). StayVerified can be implemented as a property. we have defined a very basic class called Taxi. To do this. Ideally. as the word nowadays is “agility”. Basically. This is what is called turning a condition into a function. Although the Pay method has a guard clause and PayToDriver is only invoked when it really needs to be called. The clause is basically a conditional statement that checks if the taxi has been booked beforehand. making it more readable and at the same time.Read(). this should make you a stronger and better developer. We live in a world where the rate of change and complexity has dramatically increased over the last few years. the rate in which we produce maintainable software is not necessarily the same. Console. having a good understanding of its fundamental core concepts will help you understand and successfully apply principles such as Polymorphism. } } } In this example. let’s redefine our function as an Action. If the taxi has not been booked. this represents a private taxi company that only drives customers to their destination if the customer has booked a taxi through the company’s website beforehand. This leads to better code and one that is both agile and responsive to ever-changing user requirements.ManageBooking = this. PayToDriver(). the state (handled through the property StayVerified) can be directly assigned to the Action.

6 .

and certain languages such as C++ can be used to write such applications. To know more about object read the following links: 3. by using the dot. for example. ASP and COM are examples of unmanaged code”. What is Managed or Unmanaged Code? Managed Code “The code. Unmanaged code is executed with the help of wrapper classes. "a class or struct definition is like a blueprint that specifies what the type can do.NET framework is known as unmanaged code.level functions of the operating system. Wrapper classes are of two types:  CCW (COM Callable Wrapper). Any language that is written in . In an object-oriented language such as C#. methods or properties. Its syntax is similar to C++ syntax and meets 100% of the requirements of OOPs like the following:  Abstraction  Encapsulation  Polymorphism  Inheritance 2. Example: Unboxing: Unboxing is also a process which is used to extract the value type from the object or any implemented interface . which is developed in .  RCW (Runtime Callable Wrapper).7 What is C#? C# is the best language for writing Microsoft . Unmanaged code can be unmanaged source code and unmanaged compile code. Background compatibility with the code of VB.NET framework is known as managed code. What is an Object? According to MSDN. When the CLR boxes a value means when CLR is converting a value type to Object Type. “Applications that do not run under the control of the CLR are said to be unmanaged. Objects helps us to access the member of a class or struct either they can be fields. a typical program consists of multiple objects interacting dynamically". Objects are also called instances. access low . which. and they can be stored in either a named variable or in an array or collection.NET Framework is managed code”. What is Boxing and Unboxing? Answer: Boxing and Unboxing both are used for type conversion but have some difference: Boxing: 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. This code is directly executed by CLR with the help of managed code execution. Client code is the code that uses these variables to call the methods and access the public properties of the object.Object and stores it on the heap area in application domain. Unmanaged Code The code. it wraps the value inside a System. 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. which is developed outside . C# provides the rapid application development found in Visual Basic with the power of C++.NET applications. 4.

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. 6.  An abstract class can have non-abstract methods (concrete methods) while in case of interface all the methods has to be abstract. byte.  Do not have permission to create any default constructor.  An abstract class can’t be used for multiple inheritance while interface can be used as multiple inheritance.  Classes can be inherited to other class.  A class can be abstract type. which is user defined. What is the difference between a struct and a class in C#? Answer: Class and struct both are the user defined data type but have some major difference: Struct  The struct is value type in C# and it inherits from System. What is the difference between Interface and Abstract Class? Answer: Theoretically their are some differences between Abstract Class and Interface which are listed below:  A class can implement any number of interfaces but a subclass can at most use only one abstract class. The enum keyword is used to declare an enumeration. But if you used beside int it has to be cast.  A structure can't be abstract. .Object Type.Value Type. What is enum in C#? Answer: An enum is a value type with a set of related named constants often referred to as an enumerator list. 7. Boxing may be done implicitly.  We can create a default constructor. Class  The class is reference type in C# and it inherits from the System.  No need to create object by new keyword.  In an abstract class we need to use abstract keyword to declare abstract methods while in an interface we don’t need to use that. double etc. we can’t change them manually.  We can’t use an object of a class with using new keyword.  Classes are usually used for large amounts of data. An enum type can be an integer (float.  An abstract class use constructor while in an interface we don’t have any type of constructor.  In an abstract class all data member or functions are private by default while in interface all are public. 5.). It is a primitive data type.8 type.  Struct can’t be inherited to other type. but unboxing have to be explicit by code.  Struct is usually used for smaller amounts of data.  An abstract class can declare or use any variables while an interface is not allowed to do so. int.

for (int i = 0. you can 'jump over one iteration' and then resume your loop execution. you can 'jump out of a loop' whereas by using continue statement.  8. if (i == 4) { 12. 1. Console.  Enums are strongly typed constant. } 20. 3. 5. } 18. Console. Wed. Fri}.Linq. using System. i. 15. } 14.  Enum values are fixed. enum Dow {Sat. Tue. and the value of each successive enumerator is increased by 1. The number is 2. long. They are strongly typed. break. i <= 5. . } Output The number is 0.Enum methods on enums. 6. { 8.Text.  The default type is int. Break Statement 1.e. 2. Their must be a numeric value for each enum type. Thu. using System. uint. 4.Collections. By default. and ulong. ushort. the first enumerator has the value 0.  Every enum type automatically derives from System. } 19. short.ReadLine(). Enum can be displayed as a string and processed as an integer. Class brk_stmt { 9.  Enums are not for end-user. sbyte. Eg. they are meant for developers. using System. All the members of enum are of enum type. The number is 3. using System. using System. 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. 17.Continue Statement 1. public static void main(String[] args) { 10.WriteLine("The number is " + i). and the approved types are byte. Some points about enum  Enums are enumerated data type in c#. 16.NET framework. Eg. namespace break_example 7. Mon. The default underlying type of the enumeration element is int. Sun. What is the difference between “continue” and “break” statements in C#? Answer: Using break statement. 21.Enum and thus we can use System. i++) { 11. The number is 1.9 An enum is used to create numeric constants in .  Enumerations (enums) make your code much more readable and understandable. 13.

{ 12.WriteLine(“The number is "+ i). i++) 13. class Test { 2. } 12. namespace continue_example 7. } . } 23. 11.ReadLine(). cons = 100. read). i <= 5. Class cntnu_stmt 9. 6. readonly int read = 10.WriteLine("const : {0}". 4. Readonly is known as “readonly” keyword in C# which is also known immutable values and are known at compile and run time and do not change their values at run time like in any function for the life of application till the application is running. The number is 2. 25. 3. for (int i = 0. Console. } 22. What is the difference between constant and read only in c#? Answer: Constant (const) and Readonly (readonly) both looks like same as per the uses but they have some differences: Constant is known as “const” keyword in C# which is also known immutable values which are known at compile time and do not change their values at run time like in any function or constructor for the life of application till the application is running. public static void main(String[] 11. Output The number is 1. using System. 4. { 14. 10. { 8. cons). public void Check() { 9. The number is 5.Text. } 26. 17. 27. 21. 3.Linq. if (i == 4) 15. continue. using System. public Test() { 5. { 10. Console. using System. 6.WriteLine("Read only : {0}".Collections. See the example We have a Test Class in which we have two variables one is readonly and another is constant. 5. Console. { 16. 19.10 2. } 24. const int cons = 10. read = 100. 1. } 18. 7. 9. } 8. Console. You can assay their value by constructor when we call constructor with “new” keyword. The number is 3. 20.

11.WriteLine("Read only : {0}".ReadLine(). class Test { 9. static void Main(string[] args) { 3. 16. public void Check() { 15. } 18.WriteLine("const : {0}". const int cons = 10. read). read = 100. We have lots of differences in both of them. } 8. } 14. } Output: 10. cons). Console. } 7.Check(). 5.11 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. public Test() { 12. 13. Test obj = new Test(). readonly int read = 10. Console. 17. So finally remove that line of code from class and call this Check() function like the following code snippet: 1. class Program { 2. obj. Console. The parameters can be in parameter (which is not returned back to the caller of the function). 4. 10. . What is the difference between ref and out keywords? Answer: In C Sharp (C#) we can have three types of parameters in a function. 6. out parameter and ref parameter.

An extension method is a special kind of static method. The "this" keyword is a special type of reference variable that is implicitly defined within each constructor and non- static method as a first parameter of the type class in which it is defined. The type of the first parameter will be the type that is extended. Let’s have a look on “this” keyword. How to use extension methods? An extension method is a static method of a static class. 6. return ("I m in Display"). Can “this” be used within a static method? Answer: We can't use this in static method because keyword 'this' returns a reference to the current instance of the class containing it. A Get accessor specifies that we can access the value of a field publically. public string Print() { 7. } . but they are called as if they were instance methods on the extended type. public class Class1 { 2. consider the following class written in C#. in other words it returns a single value. but in case of Extension Methods we can use it the functions parameters. the set accessor specifies that we can assign a value to a private field in a property and without the set accessor property it is like a read-only field. Static methods (or any static member) do not belong to a particular instance.  WriteOnly 13. in other words by the property we can access private fields. By the get accessor we can access the value of the private field.  ReadOnly. Like: suppose we have a class like bellow: 1. recompiling. For example. Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive. write or compute the values of private fields.12 11.net? Answer: Properties are members that provide a flexible mechanism to read. } 9. It uses methods to access and assign values to private fields called accessors. These are always public data members. They exist without creating an instance of the class and call with the name of a class not by instance so we can’t use this keyword in the body of static Methods. Now question is what are accessors? The get and set portions or blocks of a property are called accessors. These are useful to restrict the accessibility of a property. We have the three types of properties  Read/Write. where the "this" modifier is applied to the first parameter. 4. In other words we can say that a property is a return type function/method with one parameter or without a parameter. 12. Define Property in C#. public string Display() { 3. 8. What is extension method in c# and how to use them? Answer: Extension methods enable you to add methods to existing types without creating a new derived type. or otherwise modifying the original type. } 5. return ("I m in Print").

database connections in application domain and more.Display(). 8. public static class XX { 2. Console. 7. class Program { 2. held by an object before that object is destroyed. } 9. 1. now let’s see how to use this function. Finalize:  Finalize used to free unmanaged resources those are not in use like files. } 5. ob. ob.NewMethod(). public static void NewMethod(this Class1 ob) { 3. ob. } Here I just create a method that name is NewMethod with a parameter using this to define which type of data I need to be extend. Class1 ob = new Class1(). 4. . 6. 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.Print(). 4. } Output will be: 14.WriteLine("Hello I m extended method"). static void Main(string[] args) { 3.ReadKey(). Console.13 Now we need to extend the definition of this class so m going to create a static class to create an extinction method like: 1. 5.

StringBuilder: System. and make sure that these resources are freed when the Garbage collection happens. when we have to do some operations to change string simply it will dispose the old value of string object and it will create new instance in memory for hold the new value in string object like: Note:  It’s an immutable object that hold string value.Text.Object class.  Dispose explicitly it is called by manual user code.  If we need to dispose method so must implement that class by IDisposable interface.Text.  Implement it when you have unmanaged resources in your code.String.  It belongs to IDisposable interface.  Finalize belongs to System. What is the difference between string and StringBuilder in c#? Answer: StringBuilder and string both use to store string value but both have many differences on the bases of instance creation and also for performance: String: String is an immutable object. database connections in Application domain at any time.Stringbuilder is mutable object which also hold the string value.  String belongs to System namespace.14  In the Internal process it is called by Garbage Collector and can’t called manual by user code or any service. replace or append any value with existing value in string object.Text.Text.  Performance wise string is slow because its’ create a new instance to override or change the previous value.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. Immutable like when we create string object in code so we cannot modify or change that object in any operations like insert new value. 15.Stringbuilder for every time so it’s use the previous object so it’s work fast as compare than System. Let’s have an example to understand System. Dispose:  Dispose is also used to free unmanaged resources those are not in use like files. mutable means once we create a System.  Implement this when you are writing a custom class that will be used by other users.Stringbuilder like: .

15  StringBuilder is a mutable object. What is sealed class in c#? Answer: Sealed classes are used to restrict the inheritance feature of object oriented programming. structs are sealed.Stringbuilder namespace.  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. What is delegates in C# and uses of delegates? Answer: C# delegates are same as pointers to functions. { .Text. All delegates are implicitly derived from the System.  StringBuilder belongs to System. In Visual Basic . the sealed modifier is used to define a class as sealed. If you have ever noticed. If a class is derived from a sealed class then the compiler throws an error. Let’s see how to use Delegate with Example: 17. You cannot derive a class from a struct. The reference can be changed at runtime which is hold by an object of delegate. Delegates are especially used for implementing events and the call-back methods. Once a class is defined as a sealed class.Delegate class. // Sealed class 2. a delegate object can hold many functions reference which is also known as Invocation List that refers functions in a sequence FIFO. in C or C++. The following class definition defines a sealed class in C#: 1. the class cannot be inherited. 16. sealed class SealedClass 3.NET the Not Inheritable keyword serves the purpose of sealed. A delegate Object is a reference type variable that use to holds the reference to a method. In C#. we can new functions ref in this list at run time by += operator and can remove by - = operator.

Example: .16 4. What is boxing and unboxing? Answer: Boxing and Unboxing both using for type converting but have some difference: Boxing: 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. What are partial classes? Answer: A partial class is only use to splits the definition of a class in two or more classes in a same source code file or more than one source files. You can create a class definition in multiple files but it will be compiled as one class at run time and also when you’ll create an instance of this class so you can access all the methods from all source file with a same object. Example: Unboxing: Unboxing is also a process which is use to extracts the value type from the object or any implemented interface type. 5. Boxing may be done implicit but unboxing have to be explicit by code. it wraps the value inside a System. When the CLR boxes a value means when CLR converting a value type to Object Type.Object and stores it on the heap area in application domain. let’s have an example: 19. }  18. Partial Classes can be create in the same namespace it’s doesn’t allowed to create a partial class in different namespace. So use “partial” keyword with all the class name which you want to bind together with the same name of class in same namespace.

 Run Time also known as Late Binding or Overriding.Generic. HastTable etc.Collections.17 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. Polymorphism we have 2 different types to achieve that:  Compile Time also known as Early Binding or Overloading. that can be enumerated.Collections. For the generic version of this interface as IEnumerable<T> which a parent interface of all generic collections class in System.IEnumerable<T> have only a single method which is GetEnumerator() that returns an IEnumerator.Generic namespace like List<> and more. 21. IEnumerator provides the power to iterate through the collection by exposing a Current property and Move Next and Reset methods. if we doesn’t have this interface as a parent so we can’t use iteration by foreach loop or can’t use that class object in our LINQ query. 20.Collections namespace like ArrayList. What is difference between late binding and early binding in c#? Answer: Early Binding and Late Binding concepts belongs to polymorphism so let’s 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. Compile Time Polymorphism or Early Binding: In Compile time polymorphism or Early Binding we will use multiple methods with same name but different type of parameter or may be the number or parameter because of this we can perform different-different tasks with same method name in the same class which is also known as Method overloading. What is IEnumerable<> in c#? Answer: IEnumerable is the parent interface for all non-generic collections in System. In System. See how we can do that by the following example: .

the results of that query can be enumerated.Collections. Like as following example:  22.Generic namespace like List<> and more.Collections namespace like ArrayList. the standard query operators cannot be used on the provider's data source. Queries that do not return enumerable results are executed when the Execute method is called. that can be enumerated. It is only supposed to be implemented by providers that also implement IQueryable<T>. The definition of "executing an expression tree" is specific to a query provider. .18 Run Time Polymorphism or Late Binding: Run time polymorphism also known as late binding. What are the differences between IEnumerable and IQueryable? Answer: Before the differences learn what is IEnumerable and IQueryable. If the provider does not also implement IQueryable<T>. IEnumerable: Is the parent interface for all non-generic collections in System. HastTable etc. it may involve translating the expression tree to an appropriate query language for the underlying data source. Enumeration causes the expression tree associated with an IQueryable object to be executed. For example. For the generic version of this interface as IEnumerable<T> which a parent interface of all generic collections class in System. The IQueryable interface inherits the IEnumerable interface so that if it represents a query. in Run Time polymorphism or Late Binding we can do use same method names with same signatures means same type or same number of parameters but not in same class because compiler doesn’t allowed that at compile time so we can use in derived class that bind at run time when a child class or derived class object will instantiated that’s way we says that Late Binding. IQueryable: As per MSDN IQueryable interface is intended for implementation by query providers. For that we have to create my parent class functions as partial and in driver or child class as override functions with override keyword.

class Program { 2. void testInterface2. 5. 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 don’t need to define all or in other words we can say if we have conflict methods in same class so we can’t 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 let’s see an example: 1. Console. void Show(). void testInterface1.WriteLine("For testInterface2 !!").Show() { 11. Console. } 4. interface testInterface2 { 5. } Output: . 15. void Show(). } Now see how to use those in a class: 1. 9. testInterface1 obj1 = new Abc(). class Abc: testInterface1. 6. obj2. 8.ReadLine(). 8. } 13.19 23. obj1.Show(). 6. interface testInterface1 { 2. 7. 4. } 16. 3. } 10. testInterface1 obj2 = new Abc(). 10. } 7. static void Main(string[] args) { 3. testInterface2 { 9.WriteLine("For testInterface1 !!"). Console.Show() { 14.Show(). 12.

Net? Answer: Arrays are powerful data structures for solving many programming problems.  Arrays are reference types and are instances of System. Access to array elements is by their index value that ranges from 0 to (length-1). Arrays Overview An array contains zero or more items called elements. C# supports single-dimensional (vectors).20 24. but it does not copy the objects that the references refer to. either value or reference type. All the elements in an array are of the same type (unlike fields in a class that can be of different types). What are the Arrays in C#. 26. In C# arrays are immutable such that the number of dimensions and size of the array are fixed.  An array length can be determined by the GetLength() method or Length property. The CopyTo method copies all the elements of an array to another one-dimension array. float and string type and so on. A shallow copy of an Array copies only the elements of the Array. whether they are reference types or value types. An array is an unordered sequence of elements. multidimensional and jagged arrays.  Elements are initialized to default values. The references in the new Array point to the same objects that the references in the original Array point to. What is the Constructor Chaining in C#? Answer: constructor chaining is a way to connect two or more classes in a relationship as Inheritance. What’s the difference between the System.Clone()? Answer: Clone: Method creates a shallow copy of an array.Array.Array. they hold information about a single item. So what is the solution if you need to manipulate sets of items? One solution would be to create a variable for each item in the set but again this leads to a different problem. Elements are identified by indexes relative to the beginning of the arrays. How many variables do you need? So in this situation Arrays provide mechanisms that solves problem posed by these questions. An index is also commonly called indices or subscripts and are placed inside the indexing operator ([]). You saw during the creation of variables of many types that they have one thing in common. Array Properties  The length cannot be changed once created.CopyTo() and System. in Constructor Chaining every child class constructor is mapped to parent class Constructor implicitly by base keyword so when you create an instance of child class to it’ll call parent’s class Constructor without it inheritance is not possible. An array is a collection of related items. for instance an integer.  25.Array. CopyTo: The Copy static method of the Array class copies a section of an array to another array. The code listed in Listing 9 copies contents of an .  Their number of dimensions or ranks can be determined by the Rank property. The elements of an array accessed using an integer index that always starts from zero.

Can Multiple Catch Blocks executed in c#? Answer: 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. .WriteLine("Result is {0}".WriteLine("\n----------------------\n").5. Calculate.WriteLine("Addition : " + Calculate.WriteLine("Finally Block"). • A public static means of getting the reference to the single created instance. 11. int x = 0. div = 100 / x. 28. Calculate. 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. 9.WriteLine("DivideByZeroException"). Console. Console. static void Main(string[] args) { 4. This is the example how to write the code with Singleton: 1. using System.WriteLine("Not executed line"). 6. 12.WriteLine("Addition : " + Calculate.Instance. What is Singleton Design Patterns and How to implement in C#? Answer: What is Singleton Design Pattern? 1. There are various ways to implement the Singleton Pattern in C#. Console.WriteLine("Multiplication : " + Calculate. class MyClient { 3.Addition()). int div = 0. Console. 17.Instance.Multiplication()). 3.ValueOne = 10. 5.Division()). try { 7.WriteLine("Exception"). } 19. } 16. Console. 8.) 4. div).ValueTwo = 10. Ensures a class has only one instance and provides a global point of access to it. • A single constructor. 5. } finally { 14. 2. singletons don't allow any parameters to be specified when creating the instance. Console. 10. 2.Addition()). Calculate.5. Most commonly. 7. A singleton is a class that only allows a single instance of itself to be created. Console.Instance. } catch (DivideByZeroException de) { 10.WriteLine("Subtraction : " + Calculate. 11.Instance.Subtraction()). Console. 14.Instance. creating one if necessary. namespace Singleton { 2. • A static variable that holds a reference to the single created instance.5. that is private and parameterless.Instance. 15. Console. • The class is sealed. Console. 9. } catch (Exception ee) { 12. 6. 13.ValueTwo = 5. } 18. 13.Instance. class Program { 3.Instance. and usually gives simple access to that instance. public static void Main() { 4. Console. The following are the common characteristics of a Singleton Pattern.21 integer array to an array of object types. 8.WriteLine("Division : " + Calculate. if any. 27.

Instance. Let us see what it means rather speaking so many words to better understand the differences. instance = new Calculate(). get. public double ValueOne { 36. 37. } 59. 42. return ValueOne / ValueTwo. 32. 58. public double Multiplication() { 53. 23. using System. 18.ReadLine(). using System.Text. } 39. } 51.Instance. namespace TestingThrowExceptions { . return ValueOne * ValueTwo. 6. public double Division() { 57. 54. 1. 20. return ValueOne . 35. } 34. } 55. 30. public sealed class Calculate { 24. 4. 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. 52. 5. } 43.22 15. get { 28. 19. Console. Console.ValueTwo. Difference between Throw Exception and Throw Clause.WriteLine("Division : " + Calculate. return instance. private Calculate() {} 25. using System.Instance. 38. 41. using System. public double Addition() { 45. 56.Multiplication()). } 47. set.WriteLine("Multiplication : " + Calculate. Throw basically retains the stack information and adds to the stack information in the exception that it is thrown. 46. 48. set. return ValueOne + ValueTwo.Division()). } 31. Console.Linq. 26. 2. } 33. 17.Collections. }  29. get. I am using a console application to easily test and see how the usage of the two differ in their functionality. public double ValueTwo { 40. } 21. 50. 16. public double Subtraction() { 49. if (instance == null) { 29. public static Calculate Instance { 27.Subtraction()).Generic. Console.WriteLine("Subtraction : " + Calculate. private static Calculate instance = null. 44. } 22. 3.

What is multicast delegate in c#? Answer Delegate can invoke only one method reference has been encapsulated into the delegate. Creating an Indexer 1. is a class property that allows you to access a member variable of a class using the features of an array. return type > this[argument list] { 3. } In the above code: <modifier> can be private. 31. 13. class Program { 8. get { 4. <return type> can be any valid C# types.23 7. // your get block code 5. 15. } 22. also called an indexed property. public void ExceptionMethod() { 9. throw ex. They are not essential part of object-oriented programming. C# introduces a new concept known as Indexers which are used for treating an object as an array. protected or internal. set { 8. } Now run the code by pressing the F5 key of the keyboard and see what happens.it is possible for certain . throw new Exception("Original Exception occurred in ExceptionMethod").Net? Answer: Indexer allows classes to be used in more intuitive manner. p. } catch (Exception ex) { 18. 10. It returns an exception and look at the stack trace: 30. Program p = new Program(). The indexers are usually known as smart arrays in C#. } 23. 17. try { 16. 20. // your set block code 9. } 6. } 12. 11. } 21. What are Indexer in C# . < modifier > < 2. static void Main(string[] args) { 14. 19. } 10. Instances of that class can be accessed using the [] array access operator. 7. public.ExceptionMethod(). Defining an indexer allows you to create classes that act like virtual arrays. An indexer.

public static void Main() { 16. MDelegate m2 = new MDelegate(DM. 4. 2.ReadKey(). class MTest { 15. using System.WriteLine("== operator result is {0}". class Program { 4.multicast delegates also know as combinable delegates.Text. 2. Console. In this example we assigned a string variable to another variable. 8. Difference between Equality Operator (==) and Equals() Method in C#.Generic. 20. 3. static public void Display() { 8. must satisfy the following conditions:  The return type of the delegate must be void. name. 5. using System. m5(). 22. using System. MDelegate m5 = m3 .Display).Equals(myName)). namespace ComparisionExample { 3. Console.m2. Console. m3(). }  32. None of the parameters of the delegate type can be delegate type can be declared as output parameters using out keywords. string name = "sandeep". 10. Implement Multicast Delegates Example: 1. MDelegate m1 = new MDelegate(DM. static void Main(string[] args) { 5. MDelegate m3 = m1 + m2. The Equality Operator (==) is the comparison operator and the Equals() method compares the contents of a string. the invocation list is formed by concatenating the invocation list of two operand of the addition operation. 18. using System. 21.Linq. 24. 23. name == myName). 6.Collections.24 delegate to hold and invoke multiple methods such delegate called multicast delegates. The == Operator compares the reference identity while the Equals() method compares only contents. delegate void MDelegate(). Console.print). 1. 9. A string is a reference type and in the following example. } 10. 17. Answer: Both the == Operator and the Equals() method are used to compare two value type data items or reference type data items. m4(). } . 19. } 14. 12. } 13. 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. string myName = name.WriteLine("Equals method result is {0}". using System. Let’s see with some examples. } 25. } 11. 7. 9. static public void print() { 11.  Multicast delegate instance that created by combining two delegates.WriteLine("Meerut"). Delegates are invoked in the order they are added. MDelegate m4 = m2 + m1.WriteLine("Roorkee"). class DM { 7. 6. Console.

"as" operator: The "as" operator behaves similar to the "is" operator. here we get false: 1. we are just checking the matching type. class Author { 8. 2.WriteLine("speaker is of Speaker type:{0}". set. Let's understand the preceding from a small program. 4. { 3. Console. 5. 1. let's try to check the preceding types as: 1. } Now. } 6. var author = new Author { Name = "Gaurav Kumar Arora" }. If the two objects are of the same type. return (authorObj != null) ? authorObj. get. public static string GetAuthorName(dynamic obj) 2. Yes. Let's understand the preceding with a small snippet as in the following: 1. public string Name { 9. } 12.Name : string. } We have a method that accepts dynamic objects and returns the object name property if the object is of the Author type. get. var speaker = new Speaker { Name="Gaurav Kumar Arora"}. isTrue). . So. var isTrue = speaker is Speaker. 5.WriteLine("speaker is of Author type:{0}". In the preceding. Author authorObj = obj as Author. The only difference is it returns the object if both are compatible to that type else it returns null. set. 10. Because our our speaker is not an object of Author type. it returns true and false if not. Console. isTrue). 4. the results as true. public string Name { 3. But. class Speaker { 2. our speaker is an object of Speaker type. We defined the following two classes: 1. var isTrue = speaker is Author. We declared an object of Speaker as in the following: 1. 3.Empty. } 7. we use the "is" operator to check the object type.25 Answer: "is" operator In the C# language. 11.

 Types of parameter can be different. As discussed in previous section "var" is not compatible with this Nullable Type. var authorName = GetAuthorName(author). var speaker = new Speaker { Name="Gaurav Kumar Arora"}.WriteLine("Author name is:{0}". 2. Example: 1.26 Here. var i = 4. Declaration: Any DataType can be declared nullable type with the help of operator "?". Different Ways of Method can be overloaded. 2.Net? Answer: A nullable Type is a data type is that contain the defined data type or the value of null. . var author = new Author { Name = "Gaurav Kumar Arora" }. 4.  Number of parameter can be different. Method overloading is done at compile time and we have multiple way to do that but in all way method name should be same. The following returns the "Name" property: 1. though following syntax is completely fine :- 1. 35. How to use Nullable<> Types in . using System. Answer: Method overloading is a way to achieve compile time Polymorphism where we can use a method with the same name but different signature. authorName = GetAuthorName(speaker). Console. So we will have Compile Time error if we are declaring something like: - 1.Linq.Text. Console. I will explain this with syntax in next section. using System. we declared two objects: 1. It returns an empty string: 1. 2.Collections. 2. 34. authorName). using System. You should note here that here variable datatype has been given and then only it can be used. int? i = null. Example of the syntax is as Follows :- 1.  Order of parameters can be different. 3. var? i = null.WriteLine("Author name is:{0}". using System. This nullable type concept is not comaptible with "var". authorName).Generic.

net? Answer: Generics allow you to delay the specification of the data type of programming elements in a class or a method. } 14.Net? Answer: Object Pooling is something that tries to keep a pool of objects in memory to be re-used later and hence it will reduce the load of object creation to a great extent. You write the specifications for the class or the method. 13. return (l * b * h). static long volume(long l. 11. 6. namespace Hello_Word { 7. otherwise a new object will be created and give you back. 12. Whenever there is a request for a new object. generics allow you to write a class or method that can work with any data type. int h) { 24. 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. If there is any object available within the allowed limit. Console. but you can make it general by using Object base class. return (3. 15)). } 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 it’ll call that method have integer parameter instead of object type parameters method. What does it mean? Object Pool is nothing but a container of objects that are ready for use. 10. it will return the object (value object). Console. static int volume(int x) { 16. 75.ReadLine(). it generates code to handle the specific data type. which will take care about the creation of objects. 21. } 18. What is an Object Pool in . 8)). static double volume(float r. We will have a factory method.5F. When the compiler encounters a constructor for the class or a function call for the method. 17. 25. } 27. . the factory method will look into the object pool (we use Queue object). int b. In other words. What are generics in c#. until it is actually used in the program. return (x * x * x).WriteLine(volume(10)). 36.14 * r * r * h). } 22. } 26. Console. How it works? We are going to use Factory pattern for this purpose. 37.WriteLine(volume(2.WriteLine(volume(100L. 19. Console. The example is for an Employee object. public static void Main() { 9. with substitute parameters for data types. This article will try to explain this in detail. 15. class overloding { 8. int h) { 20.27 5. 23.

. Why to use access modifiers? Access modifiers are an integral part of object-oriented programming.Net. The . type safety and performance. System. Generics are most frequently used with collections and the methods that operate on them.Generic namespace.Collections. classes.  You may get information on the types used in a generic data type at run-time using reflection.28 Generic classes and methods combine reusability. that contains several new generic-based collection classes.  You may create generic classes constrained to enable access to methods on specific data types.NET Framework 2. type safety and efficiency in a way that their non-generic counterparts cannot. Access modifiers allow you to define who does or doesn't have access to certain features.  You can create your own generic interfaces.0 of the .0 and later use the new generic collection classes instead of the older non-generic counterparts such as ArrayList. Answer: Access modifiers are keywords used to specify the declared accessibility of a member or a type.  You can create generic collection classes. methods.Collections namespace. Version 2. You may use these generic collection classes instead of the collection classes in the System.Generic. In C# there are 5 different types of Access Modifiers. It is recommended that all applications that target the . Describe the accessibility modifiers in c#.Collections.NET Framework class library contains several new generic collection classes in the System.  38. which promotes the idea of hiding functionality.NET Framework class library provides a new namespace. They support the concept of encapsulation. events and delegates. Features of Generics Generics is a technique that enriches your programs in the following ways:  It helps you to maximize code reuse.

We can't use the virtual modifier with the static. 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. The overriding member in the most derived class is called. methods are non-virtual. What are the Difference between Array and ArrayList in C#. We can't override a non-virtual method. 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. if no derived class has overridden the member. 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. A virtual method is created in the base class that can be overridden in the derived class. 2. It is used when a method's basic functionality is the same but sometimes more functionality is needed in the derived class. Virtual Method 1. A virtual method has an implementation in a base class as well as derived the class. abstract. Hence it is also an example for polymorphism. By default.29 39. The overriding method also provides more than one form for a method. the run-time type of the object is checked for an overriding member. 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. When a virtual method is invoked. What is Virtual Method in C#? Answer: A virtual method is a method that can be redefined in derived classes. For More Details follow the link:  Virtual Method in C# 40.Net? Answer: Difference between Array and ArrayList . private or override modifiers. which might be the original member.

e. Suppose you have a business layer where you have many classes to perform your business data. So in a Reference Type assignment both Value and Reference will be assigned i. 2. 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. but the Reference Type member will alter according to the second instance. SO what you will you do my friend? Here comes Serialization. the state of first instance will automatically alter. It has an integer member.Net? Answer: In C# data types can be of two types: Value Types and Reference Types. So in this particular scenario. all instances have its own local copy of members. 1. 3. it seems like a swallow copy. both Reference & Value Types will be effected. Value Type With Reference Type This case and the last case to come are more interesting. 4.e. When you performing the assignments. Value Type member will located into Stack and reference member will located in Heap always. Now suppose you want to test whether your business classes give the correct data out without verifying the result from the UI or from a database. But this time it includes a Reference Type(A Custom Class Object) Member besides a Value Type (An Integer) Member. as whole items are value type and assignments on those types will copy only values not references i. I used a structure in this particular scenario also. Let consider each case briefly. You will serialize all your necessary business classes and save them into a text or XML .e. Pure Value Type Here I used a structure as a value type. but it hasn't effect the first one. Reference Type With Value Type Contrary to the above case. assignment of Reference Type member produced a reference to a single object and assignment of Value Type member produced a local copy of that member. After wards I assigned second instance to the first one. as Value Type member of first instance won't effected. What you understand by Value types and Reference types in C#. Value type variables contain their object (or data) directly. Pure Reference Type I created a class and added a "DataTable" as a Reference Type member for this class. all instances will point to the single object. Then I changed the state of second instance. But the difference is that on changing the state of second instance. in a Value Type assignment. a Value Type member in a Reference Type will be shared among its instances. I. Then I performed the assignments just like below. in this scenario. Because it will take some time to process.30 41. What is Serialization? Answer: Serialization means saving the state of your object to secondary memory. such as a file.  42. I created two instances of this structure.

2. jaggedArray[0] = new int[3]. int[][] jaggedArray = new int[5][]. jaggedArray[4] = new int[10]. 78 }. 7.You do not have to explicitly allocate and release memory for managed objects. In the above declaration the rows are fixed in size. The using statement in C# defines a boundary for the object outside of which. jaggedArray[4] = new int[] { 1. 6. }. 44. 11. But columns are not specified as they can vary. on your hard disk. jaggedArray[3] = new int[] { 1. 8. 6 }. The framework invokes the Dispose method of objects specified within the "using" statement when the block is exited. 9. jaggedArray[0] = new int[] { 3. jaggedArray[3] = new int[8]. the object is automatically destroyed.Net Framework provides resource management for managed objects through the garbage collector ." A special type of array is introduced in C#. 10.  43. To allow the programmer to explicitly perform these clean-up activities. for example . Binary serialization (Save your object data into binary format). 2. 3. 4. 6 }. Soap Serialization (Save your object data into binary format. 4. 87. The object could also be created outside the "using" statement. 78 }. You can say it is a little bit of autonomic unit testing performed by the developer. jaggedArray[2] = new int[2]. A jagged array is sometimes called an "array of arrays. So you can easily test your desired result by comparing your serialized saved data with. XmlSerialization (Save your object data into an XML file).31 file. 45. The "using" statement allows you to specify multiple resources in a single statement. 5. 4. 1. Clean-up operations for any unmanaged resources should performed in the destructor in C#. There are three types of serialization: 1. 54. 3. 0. objects can provide a Dispose method that can be invoked when the object is no longer needed. your desired output data. Example: 1. mainly used in network related communication). int[][] jagArray = new int[5][]. jaggedArray[1] = new int[] { 1. 0. Declaring and initializing jagged array. 34. jaggedArray[2] = new int[] { 1. jaggedArray[1] = new int[5]. 67. What is the use of Using statement in C#? Answer: The .an exception is thrown. 2. 6. 67. 0. The using statement is excited when the end of the "using" statement block or the execution exits the "using" statement block indirectly. 4. The elements of a jagged array can be of different dimensions and sizes. A Jagged Array is an array of an array in which the length of each array index can differ. 5. 6. 7. 12. What is jagged array in C#. The objects specified within the using block must implement the IDisposable interface. 2.  . 2.Net? Answer: A jagged array is an array whose elements are arrays.

{ 3. A thread is considered to be a lightweight process because it runs within the context of a program and takes advantage of resources allocated for that program. 46. Here Type is generating by the compiler and it is accessible only for the current block of code. in . The type of properties is also inferred by the compiler.Threading Namespace Like many other features.ForeName). This is way to defining read only properties into a single object without having to define type explicitly. var anonymousData = new 2. We can create anonymous types by using “new” keyword together with the object initializer. Example 1. What is Multithreading with . }.WriteLine("First Name : " + anonymousData.32 45. A single-threaded process contains only one thread while a multithreaded process contains more than one thread for execution.NET? Answer: The real usage of a thread is not about a single sequential thread. Console.Threading is the namespace that provides various types to help in construction of multithreaded applications. System. Multiple threads running at the same time and performing various tasks is referred as Multithreading. 6. SurName = "Trivedi" 5.NET. but rather using multiple threads in a single program. Explain Anonymous type in C#? Answer: Anonymous types allow us to create new type without defining them. 4. System. Anonymous Types with LINQ Example . ForeName = "Jignesh".

Here. data.Add(new MyData { 23. 25. FirstName = "Rakesh". data.LastName 41. }. 31. MiddleName = "G". } 45. MiddleName = "G".WriteLine("Name : " + m. DOB = new DateTime(1993.FirstName + " " + m. 34. DOB etc.Add(new MyData { 26. The hash table is a general-purpose dictionary collection. 17. set. class MyData { 2. MiddleName = "K".Net Framework has provided a Hash Table class that contains all the functionality required to implement a hash table without any additional development. LastName = "Vyas". foreach(var m in anonymousData) { 43.Add(new MyData { 35. data. // Create Dummy Data to fill Collection. Console. select new { 40. public DateTime DOB { 11. LastName = "Pandiya". }). } 6. 11. The . 28. }  47. LastName = "Trivedi". 30) 24. FirstName = "Jignesh". 15) 33. Values) pairs. 42. public string FirstName { 3. LastName = "Trivedi". } 38. 20) 36. List < MyData > data = new List < MyData > (). pl.FirstName. } 10. DOB = newDateTime(1988. public string LastName { 7. 12. 5. set. 7. 4. get. 6. } 19. var anonymousData = from pl in data 39. 16.Add(new MyData { 29. 12. public string MiddleName { 15. DOB = newDateTime(1983. MiddleName = "P". }). } 18. }). } 14. 37. get. LastName. set. 1. FirstName = "Tejas". Example If Any object collection having properties called FirstName . Each item within the collection is a DictionaryEntry object with . LastName = "Trivedi". DOB = new DateTime(1990. 8. 21. FirstName = "Yash". DOB = new DateTime(1995. the Keys are used to find the storage location and is immutable and cannot have duplicate entries in the Hashtable. 13. data. 10. and you want only FirstName and LastName after the Querying the data then. MiddleName = "G". get. FirstName = "Amit". Explain Hashtable in C#? Answer: A Hashtable is a collection that stores (Keys. }). static void Main(string[] args) { 20.Add(new MyData { 32. 22. set. 8 ) 30. get. 44. 6) 27.LastName).33 Anonymous types are also used with the "Select" clause of LINQ query expression to return subset of properties. }). data. 9. pl.

F 49.Net Framework type.IO namespace provides four classes that allow you to manipulate individual files. Compile time syntax checking. the capacity is automatically increased as required through reallocation. The data source could be collections of objects. This code is hidden from the developer.  48. XML as well as collections. They implement roughly the same public methods as a Directory and a File but they are stateful and the members of these classes are not static. enumerable classes etc in the native language of your application. as well as interact with a machine directory structure. database or XML files. to the source code. So to execute any of the examples. language-integrated way to query over data no matter where that data came from.Net? Answer: The System. like VB or C# in much the same way as you would query a database using SQL.Collections namespace. Hashtable HT = new Hashtable (). a hash code is generated automatically.Collections. The Hashtable Collection The Base Class libraries offers a Hashtable Class that is defined in the System. The FileInfo and DirecotryInfo types are derived from the abstract class FileSystemInfo type and they are typically. These are known as Key/Value. Advantages of LINQ 1. They only contain static methods and are never instantiated. .Collections. As the items in the collection are sorted according to the hidden hash code. We can easily retrieve data from any object that implements the IEnumerable<T> interface. the items should be considered to be randomly ordered. LINQ is a data querying methodology which provides querying capabilities to . so you don't have to code your own hash tables. The capacity of a hash table is the number of elements the hash table can hold. What is LINQ in C#? Answer: LINQ stands for Language Integrated Query. moving and deletion of files using various static methods. employed for obtaining the full details of a file or directory because their members tend to return strongly typed objects.NET languages with a syntax similar to a SQL query LINQ has a great power of querying on any source of data. When items are added to a hash table.Object and supports the creation. It allows you to query collections like arrays. 2. copying. So through LINQ we can query database. What is File Handling in C#. The Directory and File directly extends System. we have to add using System. 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. 3. Declaring a Hashtable The Hashtable class is generally found in the namespace called System. As elements are added to a hash table. It is an older .34 two properties: a key object and a value object. LINQ offers an object-based. All access to the table's values is achieved using the key object for identification. The declaration for the Hashtable is: 1.

NET tools don't need to parse the source code similar to C++. FieldInfo[] fld = t. Fxcop and NUnit because . foreach(MethodInfo m in mth) { 13. events and properties. Console. Console.GetFields(). f. static void FieldInvestigation(Type t) { 2. Here.WriteLine("-->{0}". } 8.Name). methods. it is mandatory to import "System. Console. 6. Metadata Investigation The following program depicts the process of reflection by creating a console based application. The static method takes a single "System.Reflection".GetMethods().WriteLine("*********Methods*********").WriteLine("-->{0}". 9.exe or *. You can dynamically discover the set of interfaces supported by a given type using the System. MethodInfo[] mth = t. 4. This namespace contains numerous related types as follows: Reflection typically is used to dump out the loaded assemblies list. } 15. 12. we can access the same "type" information as displayed by the ildasm utility at design time.Net? Answer: Reflection typically is the process of runtime type discovery to inspect metadata. 11.35 50. static void MethodInvestigation(Type t) { 10. CIL code.Type" parameter and returns void. late binding and self- generating code. foreach(FieldInfo f in fld) { 5. Before proceeeding. } 7.dll assembly to explore defined significant contents information. This program will display the details of the fields. fields.Reflection namespace. 14. 1. properties and interfaces for any type within the mscorlib. What is Reflection in C#. At run time by using reflection. Console. Reflection is also used in the external disassembling tools such Reflector. we are defining a number of static methods in the program class to enumerate fields. methods and interfaces in the specified type. properties etcetera.dll assembly. The reflection is analogous to reverse engineering in which we can break an existing *.Name). } . 3. their reference to inspect methods.WriteLine("*********Fields*********"). including methods. m.

36 .