Wednesday, April 19, 2017

C# Basics Interview Questions and Answers

C# Basics Interview Questions and Answers


1 What is C#?
C# is a programming language designed by Microsoft. It is loosely based on C/C++, and bears a striking similarity to Java. Microsoft describe C# as follows:

"C# is a simple, modern, object oriented, and type-safe programming language derived from C and C++. C# (pronounced 'C sharp') is firmly planted in the C and C++ family tree of languages, and will immediately be familiar to C and C++ programmers. C# aims to combine the high productivity of Visual Basic and the raw power of C++."
You can get the ECMA C# spec in PDF form here, or use Jon Jagger's html version.

2 How do I develop C# apps?
The (free) .NET SDK contains the C# command-line compiler (csc.exe). Visual Studio has fully integrated support for C# development. On Linux you can use Mono.

3 Does C# replace C++?
There are three options open to the Windows developer from a C++ background:
• Stick with standard C++. Don't use .NET at all.
• Use C++ with .NET. Microsoft supply a .NET C++ compiler that produces IL rather than machine code. However to make full use of the .NET environment (e.g. garbage collection), a set of extensions are required to standard C++. In .NET 1.x this extended language is called Managed Extensions for C++. In .NET 2.0 ME C++ has been completely redesigned under the stewardship of Stan Lippman, and renamed C++/CLI.

• Forget C++ and use C#.
Each of these options has merits, depending on the developer and the application. For my own part, I intend to use C# where possible, falling back to C++ only where necessary. ME C++ (soon to be C++/CLI) is very useful for interop between new .NET code and old C++ code - simply write a managed wrapper class using ME C++, then use the managed class from C#. From experience, this works well.

4 Does C# have its own class library?
Not exactly. The .NET Framework has a comprehensive class library, which C# can make use of. C# does not have its own class library.

5 What standard types does C# use?
C# supports a very similar range of basic types to C++, including int, long, float, double, char, string, arrays, structs and classes. However, don't assume too much. The names may be familiar, but many of the details are different. For example, a long is 64 bits in C#, whereas in C++ the size of a long depends on the platform (typically 32 bits on a 32-bit platform, 64 bits on a 64-bit platform). Also classes and structs are almost the same in C++ - this is not true for C#. Finally, chars and strings in .NET are 16-bit (Unicode/UTF-16), not 8-bit like C++.

6. Is it true that all C# types derive from a common base class?
Yes and no. All types can be treated as if they derive from object (System.Object), but in order to treat an instance of a value type (e.g. int, float) as object-derived, the instance must be converted to a reference type using a process called 'boxing'. In theory a developer can forget about this and let the run-time worry about when the conversion is necessary, but in reality this implicit conversion can have side-effects that may trip up the unwary.

7. So I can pass an instance of a value type to a method that takes an object as a parameter?
Yes. For example:

class CApplication
{  public static void Main()    
 {    int x = 25;        
      string s = "fred";
      DisplayMe( x );        
      DisplayMe( s );    
 }
static void DisplayMe( object o )    
 {         System.Console.WriteLine( "You are {0}", o );    
 }
}

This would display:
You are 25
You are fred

8. What are the fundamental differences between value types and reference types?
C# divides types into two categories - value types and reference types. Most of the intrinsic types (e.g. int, char) are value types. Structs are also value types. Reference types include classes, arrays and strings. The basic idea is straightforward - an instance of a value type represents the actual data, whereas an instance of a reference type represents a pointer or reference to the data.

The most confusing aspect of this for C++ developers is that C# has predetermined which types are represented as values, and which are represented as references. A C++ developer expects to take responsibility for this decision.

For example, in C++ we can do this:
int x1 = 3; // x1 is a value on the stack
int *x2 = new int(3) // x2 is a pointer to a value on the heap
but in C# there is no control:
int x1 = 3; // x1 is a value on the stack
int x2 = new int();
x2 = 3; // x2 is also a value on the stack!

9. Okay, so an int is a value type, and a class is a reference type. How can int be derived from object?
It isn't, really. When an int is being used as an int, it is a value. However, when it is being used as an object, it is a reference to an integer value (on the managed heap). In other words, when you treat an int as an object, the runtime automatically converts the int value to an object reference. This process is called boxing. The conversion involves copying the int to the heap, and creating an object instance which refers to it. Unboxing is the reverse process - the object is converted back to a value.
int x = 3; // new int value 3 on the stack
object objx = x; // new int on heap, set to value 3 - still have x=3 on stack
int y = (int)objx; // new value 3 on stack, still got x=3 on stack and objx=3 on heap

10. Are C# references the same as C++ references?
Not quite. The basic idea is the same, but one significant difference is that C# references can be null . So you cannot rely on a C# reference pointing to a valid object. In that respect a C# reference is more like a C++ pointer than a C++ reference. If you try to use a null reference, a NullReferenceException is thrown.
For example, look at the following method:

void displayStringLength( string s )
{
Console.WriteLine( "String is length {0}", s.Length );
}      

The problem with this method is that it will throw a NullReferenceException if called like this:

string s = null;
displayStringLength( s );

Of course for some situations you may deem a
NullReferenceException to be a perfectly
acceptable outcome, but in this case it might
be better to re-write the method like this:

void displayStringLength( string s )
{
if( s == null )
Console.WriteLine( "String is null" );
else
Console.WriteLine( "String is length {0}", s.Length );
}  



What are Namespaces?
A) Naming convention used in .Net
B) Group of classes categorized to avoid name clash
C) None of the above

C. None of the above A Namespace in .Net is like containers of objects. They may contain unions, classes, structures, interfaces, enumerators and delegates. Main goal of using namespace in .Net is for creating a hierarchical organization of program. In this case a developer does not need to worry about the naming conflicts of classes, functions, variables etc., inside a project.

What are Indexers? What is the use of it, and when to use it
An indexer is a member that enables an object to be indexed in the same way as an array. There are times when it is desirable to access a collection within a class as though the class itself were an array. For example, suppose you create a list box control named myListBox that contains alist of strings stored in a one-dimensional array, a private member variable named myStrings. Alist box control contains member properties and methods in addition to its array of strings.However, it would be convenient to be able to access the list box array with an index, just as if thelist box were an array. This can be achieved using the Indexer

What is difference between dispose() & finalize()
If you want to delete resources(objects) those are not using ,you should not worry about that, garbage collecter implicitly call finalize() method and remove all such object but if you want to delete object forcefully.The larger object ,you want to delete after completeing task),than you can explicitly call dispose() method.
Design Pattern : If your classes use unmanaged resources, you need to implement both Dispose & Finalize. Dispose() is called by user code, that is, the code that is using your class.
Finalize/Destructor cannot be called by User code, it's called by Garbage Collector
Finalize : Is a destructor, called by Garbage Collector when the object goes out of scope. Implement it when you have unmanaged resources in your code, and want to make sure that these resources are freed when the Garbage collection happens.
Dispose : Same purpose as finalize, to free unmanaged resources. However, implement this when you are writing a custom class, that will be used by other users. Overriding Dispose() provides a way for the user code to free the unmanaged objects in your custom class.

As an aside, here's how the GC works:

The garbage collector keeps track of objects that have Finalize methods, using an internal structure called the finalization queue. Each time your application creates an object that has a Finalize method, the garbage collector places an entry in the finalization queue that points to that object. The finalization queue contains entries for all the objects in the managed heap that need to have their finalization code called before the garbage collector can reclaim their memory.
Implementing Finalize methods or destructors can have a negative impact on performance and you should avoid using them unnecessarily. Reclaiming the memory used by objects with Finalize methods requires at least two garbage collections. When the garbage collector performs a collection, it reclaims the memory for inaccessible objects without finalizers. At this time, it cannot collect the inaccessible objects that do have finalizers. Instead, it removes the entries for these objects from the finalization queue and places them in a list of objects marked as ready for finalization. Entries in this list point to the objects in the managed heap that are ready to have their finalization code called. The garbage collector calls the Finalize methods for the objects in this list and then removes the entries from the list. A future garbage collection will determine that the finalized objects are truly garbage because they are no longer pointed to by entries in the list of objects marked as ready for finalization. In this future garbage collection, the objects' memory is actually reclaimed.

Dispose() is called by the user of an object to indicate that he is finished with it, enabling that object to release any unmanaged resources it holds. Finalize() is called by the run-time to allow an object which has not had Dispose() called on it to do the same. However
Dispose() operates determinalistically, whereas there is no guarantee that Finalize() will be called immediately when an object goes out of scope - or indeed at all, if the program ends before that object is GCed - and as such Dispose() is generally preferred.

In which scenerio we use interfaces, abstract and concrete class? Which one is better and appropriate? Differentiate these three terms in depth.

The decision tree for this is pretty detailed. :) In most cases, using an abstract class is the "right" thing to do if you're trying to create a common class from which others will derive and which isn't fully specified. Interfaces are nice if you don't want to force classes to have a single root class in their hierarchy, as a single class can implement multiple interfaces. Concrete classes should be used if it's fully specified--i.e. subclasses don't have any hooks into which they must provide functionality.
Interface - used to define a skeleton. Classes who want to confirm to that skeleton implementsts the interface
Abstract class - Use abstract class when you want to provide some functionality to the user and at the same time would like to enforce some skeleton (structure) for the users of your class
Concrete class - Use a concrete class to represent an object (data & methods) which can be extended or reused.
Use following guidelines for each of the abstractions:
Interface:
-- If your child classes should all implement a certain group of methods/functionalities, but each of the child classes is free to provide its own implementation, then use interfaces.

For e.g., if you are implementing a class hierarchy for vehicles, implement an interface called "Vehicle", which has properties like Colour, MaxSpeed etc., and methods like Drive(). All child classes like "Car", "Scooter", "AirPlane", "SolarCar" etc. should derive from this base interface, but provide a seperate implementation of the methods and properties exposed by Vehicle.

-- If you want your child classes to implement multiple, unrelated functionalities, in short multiple inheritance, use interfaces.
For e.g., if you are implementing a class called "SpaceShip", that has to have functionalities from a "Vehicle",
as well as that from a "UFO", then make both "Vehicle" and "UFO" as interfaces, and then create a class "SpaceShip" that implements both "Vehicle" and "UFO".

Abstract Classes
-- When you have a requirement where your base class should provide default implementation of certain methods, whereas other methods should be open to being overridden by child classes, use abstract classes.
For e.g., again take the example of the "Vehicle" class above. If we want all classes deriving from "Vehicle" to implement the "Drive()" method in a fixed way, whereas the other methods can be overridden by child classes. In such a scenario, we implement the "Vehicle" class as an abstract class with an implementation of "Drive", while leave the other methods / properties as abstract so they could be overridden by child classes.
-- The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share. For example, a class library may define an abstract class that is used as a parameter to many of its functions, and require programmers using that library to provide their own implementation of the class by creating a derived class.

What is the difference between Abstract and Interface? Answer
In an interface class, all methods are abstract - there is no implementation.
In an abstract class some methods can be concrete - there can be implementation.
In an interface class, no accessibility modifiers are allowed - are public by default.
In an abstract class accessibility modifiers are allowed.

Abstract Class:
1. Abstract Class Can contain Abstract Methods and Non-Abstract Methods.
2. When a Non-Abstract Class is Inherited from an Abstract Class, the Non-Abstract Class should provide all the implementations for the inherited Abstract Method.

Interface:
1. Interface is nothing but Pure Abstract Class ie Interface can contain only the function declaration.
2. All the members of the interface are Public by Default and you cannot provide any access modifiers.
3. When a class is inherited from the interface, the inherited class should provide actual implementations for the inherited members.

What is the main difference between pointer and delegate with examples?
Delegates in c# are very similar to function pointers in c++ the only difference is that delegates are type safe due to these are CLR targated under .net framework, while function pointers in c++ are not type safe.
A Delegate in c# allows to pass a method of class to object of other class.
Rules in Deligation:-
1. In order to create a Delegate a Signature(parameter) must match Signature of object.
2. Define all the methods which has the same Signature as Deligate define.
3. Create the deligate object & pass the method as a parameter to Deligate.
4. Now call the encapsulated method using deligated object.
The best example of Deligation model is ADO.NET Architecture & Event Handling in windows environment.
Simply say Delegate is a strongly typed function pointer and pointer holds reference to a variable or pointer is a variable which holds the address of another variable.

Delegate to function--- is same as---- pointer to object. Delegates are function pointers. They are used when the function which needs to be called is not know at compile time. Pointers, on the other hand, are used to point to variables or object references in unsafe code.

What is managed code?Skill/Topic: Intermediate
A) Code managed ouside the IL
B) Code which can't be managed by the IL
C) Code written in VB.NET
D) Code to be compiled by IL

D) is the correct choice. Managed code is the code written in one of 20 high level programming languages available for use with .Net framework which is compiled into IL during the first level of compilation.

Ans : (A) The managed code are the code which are managed by the CLR not by the executalble code itself.(Ref.- MCSD Training Kit Developing Web Applicaion of PHI)
A is correct ans,

Ex: vbc compiler is compile to vb.net application in to MSIL(IL) code
csc compiler is compile to c#.net application code in to MSIL code
DotNet support multiple languages , each compiler will convert MSIL(IL) Code only. after CLR execute the code in memory before taking code in CLR, JIt will compile machine understandble code.

Jobs in india

IT / Software Jobs,Core Technical Jobs, Government Jobs,Defence Jobs,Research Jobs,BPO Jobs,Bank Jobs, Tech Support Jobs,Health Care Job...