Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Friday, April 3, 2009

.NET Basic terminology

1 What is the CLR?

Ans. CLR = Common Language Runtime. The CLR is a set of standard resources that (in theory) any .NET program can take advantage of, regardless of programming language. Robert Schmidt (Microsoft) lists the following CLR resources in his MSDN PDC# article:
· Object-oriented programming model (inheritance, polymorphism, exception handling, garbage collection)
· Security model
· Type system
· All .NET base classes
· Many .NET framework classes
· Development, debugging, and profiling tools
· Execution and code management
· IL-to-native translators and optimizers
What this means is that in the .NET world, different programming languages will be more equal in capability than they have ever been before, although clearly not all languages will support all CLR services.

2. What is the CTS?

Ans. CTS = Common Type System. This is the range of types that the .NET runtime understands, and therefore that .NET applications can use. However note that not all .NET languages will support all the types in the CTS. The CTS is a superset of the CLS.

3. What is the CLS?

Ans. CLS = Common Language Specification. This is a subset of the CTS which all .NET languages are expected to support. The idea is that any program which uses CLS-compliant types can interoperate with any .NET program written in any language.
In theory this allows very tight interop between different .NET languages - for example allowing a C# class to inherit from a VB class.

4. What is IL?

Ans. IL = Intermediate Language. Also known as MSIL (Microsoft Intermediate Language) or CIL (Common Intermediate Language). All .NET source code (of any language) is compiled to IL. The IL is then converted to machine code at the point where the software is installed, or at run-time by a Just-In-Time (JIT) compiler.

5. What is C#?

Ans. C# is a new language designed by Microsoft to work with the .NET framework. In their "Introduction to C#" whitepaper, 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++."
Substitute 'Java' for 'C#' in the quote above, and you'll see that the statement still works pretty well :-).

6. What does 'managed' mean in the .NET context?

Ans. The term 'managed' is the cause of much confusion. It is used in various places within .NET, meaning slightly different things.
Managed code: The .NET framework provides several core run-time services to the programs that run within it - for example exception handling and security. For these services to work, the code must provide a minimum level of information to the runtime. Such code is called managed code. All C# and Visual Basic.NET code is managed by default. VS7 C++ code is not managed by default, but the compiler can produce managed code by specifying a command-line switch (/com+).
Managed data: This is data that is allocated and de-allocated by the .NET runtime's garbage collector. C# and VB.NET data is always managed. VS7 C++ data is unmanaged by default, even when using the /com+ switch, but it can be marked as managed using the __gc keyword.
Managed classes: This is usually referred to in the context of Managed Extensions (ME) for C++. When using ME C++, a class can be marked with the __gc keyword. As the name suggests, this means that the memory for instances of the class is managed by the garbage collector, but it also means more than that. The class becomes a fully paid-up member of the .NET community with the benefits and restrictions that brings. An example of a benefit is proper interop with classes written in other languages - for example, a managed C++ class can inherit from a VB class. An example of a restriction is that a managed class can only inherit from one base class.

7. What is reflection?

Ans. All .NET compilers produce metadata about the types defined in the modules they produce. This metadata is packaged along with the module (modules in turn are packaged together in assemblies), and can be accessed by a mechanism called reflection. The System.Reflection namespace contains classes that can be used to interrogate the types for a module/assembly.
Using reflection to access .NET metadata is very similar to using ITypeLib/ITypeInfo to access type library data in COM, and it is used for similar purposes - e.g. determining data type sizes for marshaling data across context/process/machine boundaries.
Reflection can also be used to dynamically invoke methods (see System.Type.InvokeMember), or even create types dynamically at run-time (see System.Reflection.Emit.TypeBuilder).

Thursday, April 2, 2009

C# Interview Questions Part I

1. What are Sealed Classes in C#?

Ans. The sealed modifier is used to prevent derivation from a class. A compile-time error occurs if a sealed class is specified as the base class of another class. (A sealed class cannot also be an abstract class)

2. What is Polymorphism? How does VB.NET/C# achieve polymorphism?

class Token
{
public string Display()
{
//Implementation goes here
return "base";
}
}
class IdentifierToken:Token
{
public new string Display() //What is the use of new keyword
{
//Implementation goes here
return "derive";
}
}
static void Method(Token t)
{
Console.Write(t.Display());
}
public static void Main()
{
IdentifierToken Variable=new IdentifierToken();
Method(Variable); //Which Class Method is called here
Console.ReadLine();
}
For the above code What is the "new" keyword and Which Class Method is
called here
A: it will call base class Display method
class Token
{
public virtual string Display()
{
//Implementation goes here
return "base";
}
}
class IdentifierToken:Token
{
public override string Display() //What is the use of new keyword
{
//Implementation goes here
return "derive";
}
}
static void Method(Token t)
{
Console.Write(t.Display());
}
public static void Main()
{
IdentifierToken Variable=new IdentifierToken();
Method(Variable); //Which Class Method is called here
Console.ReadLine();
}
A: Derive

3. In which Scenario you will go for Interface or Abstract Class?

Ans. Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes. Even though class inheritance allows your classes to inherit implementation from a base class, it also forces you to make most of your design decisions when the class is first published.
Abstract classes are useful when creating components because they allow you specify an invariant level of functionality in some methods, but leave the implementation of other methods until a specific implementation of that class is needed. They also version well, because if additional functionality is needed in derived classes, it can be added to the base class without breaking code.

4. Interfaces vs. Abstract Classes

Ans. Feature Interface Abstract class
Multiple inheritance A class may implement several interfaces. A class may extend only one abstract class.
Default implementation An interface cannot provide any code at all, much less default code. An abstract class can provide complete code, default code, and/or just stubs that have to be overridden.
Constants Static final constants only, can use them without qualification in classes that implement the interface. On the other paw, these unqualified names pollute the namespace. You can use them and it is not obvious where they are coming from since the qualification is optional. Both instance and static constants are possible. Both static and instance intialiser code are also possible to compute the constants.
Third party convenience An interface implementation may be added to any existing third party class. A third party class must be rewritten to extend only from the abstract class.
is-a vs -able or can-do Interfaces are often used to describe the peripheral abilities of a class, not its central identity, e.g. an Automobile class might implement the Recyclable interface, which could apply to many otherwise totally unrelated objects. An abstract class defines the core identity of its descendants. If you defined a Dog abstract class then Damamation descendants are Dogs, they are not merely dogable. Implemented interfaces enumerate the general things a class can do, not the things a class is.
Plug-in You can write a new replacement module for an interface that contains not one stick of code in common with the existing implementations. When you implement the interface, you start from scratch without any default implementation. You have to obtain your tools from other classes; nothing comes with the interface other than a few constants. This gives you freedom to implement a radically different internal design. You must use the abstract class as-is for the code base, with all its attendant baggage, good or bad. The abstract class author has imposed structure on you. Depending on the cleverness of the author of the abstract class, this may be good or bad. Another issue that's important is what I call "heterogeneous vs. homogeneous." If implementors/subclasses are homogeneous, tend towards an abstract base class. If they are heterogeneous, use an interface. (Now all I have to do is come up with a good definition of hetero/homogeneous in this context.) If the various objects are all of-a-kind, and share a common state and behavior, then tend towards a common base class. If all they share is a set of method signatures, then tend towards an interface.
Homogeneity If all the various implementations share is the method signatures, then an interface works best. If the various implementations are all of a kind and share a common status and behavior, usually an abstract class works best.
Maintenance If your client code talks only in terms of an interface, you can easily change the concrete implementation behind it, using a factory method. Just like an interface, if your client code talks only in terms of an abstract class, you can easily change the concrete implementation behind it, using a factory method.
Speed Slow, requires extra indirection to find the corresponding method in the actual class. Modern JVMs are discovering ways to reduce this speed penalty. Fast
Terseness The constant declarations in an interface are all presumed public static final, so you may leave that part out. You can't call any methods to compute the initial values of your constants. You need not declare individual methods of an interface abstract. They are all presumed so. You can put shared code into an abstract class, where you cannot into an interface. If interfaces want to share code, you will have to write other bubblegum to arrange that. You may use methods to compute the initial values of your constants and variables, both instance and static. You must declare all the individual methods of an abstract class abstract.
Adding functionality If you add a new method to an interface, you must track down all implementations of that interface in the universe and provide them with a concrete implementation of that method. If you add a new method to an abstract class, you have the option of providing a default implementation of it. Then all existing code will continue to work without change.

see the code
interface ICommon
{
int getCommon();
}
interface ICommonImplements1:ICommon
{
}
interface ICommonImplements2:ICommon
{
}
public class a:ICommonImplements1,ICommonImplements2
{
}

C# Interview Questions Part VII

61. Why would you use untrusted verificaion?

Ans. Web Services might use it, as well as non-Windows applications.

62. What does the parameter Initial Catalog define inside Connection String?

Ans. The database name to connect to.

63. What’s the data provider name to connect to Access database?

Ans. Microsoft.Access.

64. What does Dispose method do with the connection object?

Ans. Deletes it from the memory.

65. What is a pre-requisite for connection pooling?

Ans. Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings.

C# Interview Questions Part IV

31. Will finally block get executed if the exception had not occurred?

Ans. Yes.

32. What’s the C# equivalent of C++ catch (…), which was a catch-all statement for any possible exception?

Ans. A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}.

33. Can multiple catch blocks be executed?

Ans. No, once the proper catch code fires off, the control is transferred to the finally block (if there are any), and then whatever follows the finally block.

34. Why is it a bad idea to throw your own exceptions?

Ans. Well, if at that point you know that an error has occurred, then why not write the proper code to handle that error instead of passing a new Exception object to the catch block? Throwing your own exceptions signifies some design flaws in the project.

35. What’s a delegate?

Ans. A delegate object encapsulates a reference to a method. In C++ they were referred to as function pointers.

36. What’s a multicast delegate?

Ans. It’s a delegate that points to and eventually fires off several methods.

37. How’s the DLL Hell problem solved in .NET?

Ans. Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly.

38. What are the ways to deploy an assembly?

Ans. An MSI installer, a CAB archive, and XCOPY command.

39. What’s a satellite assembly?

Ans. When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies.

40. What namespaces are necessary to create a localized application?

Ans. System.Globalization, System.Resources.

C# Interview Questions Part III

21. What’s the difference between an interface and abstract class?

Ans. In the interface all methods must be abstract; in the abstract class some methods can be concrete. In the interface no accessibility modifiers are allowed, which is ok in abstract classes.

22. How can you overload a method?

Ans. Different parameter data types, different number of parameters, different order of parameters.

23. If a base class has a bunch of overloaded constructors, and an inherited class has another bunch of overloaded constructors, can you enforce a call from an inherited constructor to an arbitrary base constructor?

Ans. Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class.

24. What’s the difference between System.String and System.StringBuilder classes?

Ans. System.String is immutable; System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.

25. What’s the advantage of using System.Text.StringBuilder over System.String?

Ans. StringBuilder is more efficient in the cases, where a lot of manipulation is done to the text. Strings are immutable, so each time it’s being operated on, a new instance is created.

26. Can you store multiple data types in System.Array?

Ans. No.

27. What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?

Ans. The first one performs a deep copy of the array, the second one is shallow.

28. How can you sort the elements of the array in descending order?

Ans. By calling Sort() and then Reverse() methods.

29. What’s the .NET datatype that allows the retrieval of data by a unique key?

Ans. HashTable.

30. What’s class SortedList underneath?

Ans. A sorted HashTable.

c# Interview Questions Part II

11. Can you declare the override method static while the original method is non-static?

Ans. No, you can’t, the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override.

12. Can you override private virtual methods?

Ans. No, moreover, you cannot access private methods in inherited classes, have to be protected in the base class to allow any sort of access.

13. Can you prevent your class from being inherited and becoming a base class for some other classes?

Ans. Yes, that’s what keyword sealed in the class definition is for. The developer trying to derive from your class will get a message: cannot inherit from Sealed class WhateverBaseClassName. It’s the same concept as final class in Java.

14. Can you allow class to be inherited, but prevent the method from being over-ridden?

Ans. Yes, just leave the class public and make the method sealed.

15. What’s an abstract class?

Ans. A class that cannot be instantiated. A concept in C++ known as pure virtual method. A class that must be inherited and have the methods over-ridden. Essentially, it’s a blueprint for a class without any implementation.

16. When do you absolutely have to declare a class as abstract (as opposed to free-willed educated choice or decision based on UML diagram)?

Ans. When at least one of the methods in the class is abstract. When the class itself is inherited from an abstract class, but not all base abstract methods have been over-ridden.

17. What’s an interface class?

Ans. It’s an abstract class with public abstract methods all of which must be implemented in the inherited classes.

18. Why can’t you specify the accessibility modifier for methods inside the interface?

Ans . They all must be public. Therefore, to prevent you from getting the false impression that you have any freedom of choice, you are not allowed to specify any accessibility, it’s public by default.
19. Can you inherit multiple interfaces?

Ans. Yes, why not.

20. And if they have conflicting method names?

Ans. It’s up to you to implement the method inside your own class, so implementation is left entirely up to you. This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data, but as far as compiler cares you’re okay.

Friday, March 27, 2009

OOPS Interview Questions Part 1

Question: What is Encapsulation? 
Answer: Encapsulation - is the ability of an object to hide its data and methods from the rest of the world. It is one of the fundamental principles of OOPs. 
Say we create a class, named Calculations. This class may contain a few members in the form of properties, events, fields or methods. Once the class is created, we may instantiate the class by creating an object out of it. The object acts as an instance of this class, the members of the class are not exposed to the outer world directly, rather, they are encapsulated by the class. 
Example:
Public class Calculations
{
private void fnMultiply(int x, int y)
{
return x * y;
}
}
...
...
Calculations obj;
int Result;
Result = obj.fnMultiply(5,10); 

Question: What is Class? 
Answer: A class is an organized store-house in object-oriented programming that gives coherent functional abilities to a group of related code. It is the definition of an object, made up of software code. Using classes, we may wrap data and behaviour together (Encapsulation). We may define classes in terms of classes (Inheritance). We can also override the behaviour of a class using an alternate behaviour (Polymorphism).
A Base Class is a class that is inherited by another class. In .NET, a class may inherit from only one class. 

Question: What is inheritance? 
Answer: Inheritance - is the concept of passing the traits of a class to another class. 
A class comprises of a collection of types of encapsulated instance variables and types of methods, events, properties, possibly with implementation of those types together with a constructor function that can be used to create objects of the class. A class is a cohesive package that comprises of a particular kind of compile-time metadata. A Class describes the rules by which objects behave; these objects are referred to as "instances" of that class. (Reference)

Classes can inherit from another class. This is accomplished by putting a colon after the class name when declaring the class, and naming the class to inherit from—the base class—after the colon.

Question: What is a class member? What is an object? 
Answer: The entities like events, properties, fields and functions encapsulated within a class are called class members. A constructor of a class that resides within it is also a form of a class member. 

When we instantiate a class in order to use its encapsulated class members, this instantiated class entity is called the object. 

Question: Whats the difference between a class and an object? 
Answer: In any object Oriented language, an object is the backbone of everything that we see. A class is a blueprint that describes how an instance of it (object) will behave. To create a class, we define it in a "Code File", with an extension *.cs or *.vb. We make use of the keyword class. 
Example
Lets create a class named Laptop
public class Laptop
{
private string sbrand;
public Laptop() {}
public Laptop(string name)
{
sbrand = name;
}
}

From our code that references this class, we write...
Laptop lp = new Laptop("Lenovo"); //Passing a variable to the class constructor
Once the class object is created, the object may be used to invoke the member functions defined within the class. We may allocate any number of objects using the new keyword. The new keyword returns a reference to an object on the heap. This reference is not to the actual object itself. The variable being refered is stored on a stack for usage in the application. When we allocate an object to a heap, its managed by the .NET runtime. The garbage collector takes care of the object by removing it from the heap, when it is no longer reachable by any part of the code. 

Question: What is polymorphism? 
Answer: Polymorphism means allowing a single definition to be used with different types of data (specifically, different classes of objects). For example, a polymorphic function definition can replace several type-specific ones, and a single polymorphic operator can act in expressions of various types. Many programming languages implement some forms of polymorphism. 

The concept of polymorphism applies to data types in addition to functions. A function that can evaluate to and be applied to values of different types is known as a polymorphic function. A data type that contains elements of different types is known as a polymorphic data type. 

Polymorphism may be achieved by overloading a function, overloading an operator, changing the order of types, changing the types using the same name for the member in context. 
Example:
Public Class Calc
{
public void fnMultiply(int x, int y)
{ return x * y; }
public void fnMultiply(int x, int y, int z)
{ return x * y * z; }
}
...
...
Calc obj;
int Result;
Result = obj.fnMultiply(2,3,4); // The second fnMultiply would be called
Result = obj.fnMultiply(3,4); // The first fnMultiply would be called
//Here, the call depends on the number of parameters passed, polymorphism is achieved using overloading 

Question: What is Overloading? What is Overloads? What is Overload? 
Answer: Overloading - is the concept of using one function or class in different ways by changing the signature of its parameters. We can define a function with multiple signatures without using the keyword Overloads, but if you use the Overloads keyword in one, you must use it in all of the function's Overloaded signatures. 
The Overloads keyword is used in VB.NET, while the Overload keyword is used in C# (There is no other difference). The Overloads property allows a function to be described using deferent combinations of parameters. Each combination is considered a signature, thereby uniquely defining an instance of the method being defined. 
Overloading is a way through which polymorphism is achieved.