Friday, March 26, 2010


What is static Readonly fields ?
Ans : Static fields are not a perfect match for this scenario. The fields are initialized at some point before they are used, but after this initialization there is nothing to stop a client from changing them. Such a modification could cause unpredictable errors in other programs that use Color and assume that the values do not change. Readonly fields can be used to prevent such problems.
Assignments to a readonly field can only occur as part of the declaration,
or in an instance or static constructor in the same class.
A static readonly field can be assigned in a static constructor,
and a non-static readonly field can be assigned in an instance constructor.

Thus, the Color class can be enhanced by adding the readonly modifier to the static fields:
class Color
internal ushort redPart;
internal ushort bluePart;
internal ushort greenPart;
public Color(ushort red, ushort blue, ushort green) {
redPart = red;
bluePart = blue;
greenPart = green;
public static readonly Color Red = new Color(0xFF, 0, 0);
public static readonly Color Blue = new Color(0, 0xFF, 0);
public static readonly Color Green = new Color(0, 0, 0xFF);
public static readonly Color White = new Color(0xFF, 0xFF, 0xFF);

What is a constant?
Ans : A constant is a class member that represents a constant value:
a value that can be computed at compile-time.
Constants are permitted to depend on other constants within the same program as long as there are no circular dependencies.
The rules governing constant expressions are defined in constant expression
The example

class Constants
public const int A = 1;
public const int B = A + 1;
shows a class named Constants that has two public constants.
Even though constants are considered static members, a constant declaration neither requires nor allows the static modifier. Constants can be accessed through the class, as in
class Test
static void Main() {
Console.WriteLine("{0}, {1}", Constants.A, Constants.B);
which prints out the values of Constants.A and Constants.B.

Q. What is the difference between Value types and Object types?
A. Value types are built-in data types in any .Net compliant language and they are stored on the application stack, whereas the Object types are user-defined types and are by default reference types and will be stored in the managed heap.

Note: A thread of discussion started here to know the depth of my understanding about the stack and heap implementation in .NET. This discussion went on for more than 12 minutes. Basically he wanted to know memory is managed in .NET by the CLR or runtime.

Q. When is a value type used over an object type?
A. Value types are used for temporary storage. They are valid only in the scope of the function or the execution block in which they are declared. Whereas the reference types are used for user-defined types which need to retain the state across function calls and have a lifetime which is defined by the usage.

Note: I also explained him about the Garbage collection mechanism here and how GC works: Application roots, marking for removal, Compaction and Finalization etc.

Q. What are different keywords used related to inheritance in C#?
A. Virtual, override, new, sealed and abstract.

Q. Given an unsigned 16 bit integer, what is the max value it can hold?
A. 65535

Q. What happens if I store more than max value in the previous scenario?
A. In .Net this scenario can be addressed in two ways: If the same is done in a checked context, the runtime will throw an OverflowException, whereas if run in unchecked context, the MSB is truncated and rest of the value is stored in the variable and the execution continues…

Note: He asked whether I was sure about this and I said, yes. But he said “Check this out to-night and you will be surprised to see the result”. Which in fact I did and didn’t find any surprise. May be there’s some undocumented feature of .NET here.

Q. What does the new keyword do w.r.t inheritance?
A. It hides the base class’s implementation.

Q. Rate yourself in OOAD and UML on a scale of 10?
A. 7-8.

Q. What is the difference between Inheritance and Composition?
A. Inheritance is a generalization relationship, used for code reuse. I cited an example of Shape as the base class and Circle, Rectangle as the derived classes. Explained him about generalization to specialization.

Composition is a strong form of containment, where the part’s lifetime is dependent on the whole. Cited and example.

Q. What is polymorphism?
A. Compile time polymorphism (Function/operator overloading examples).
Runtime polymorphism (Late binding, Virtual/Overridden functions examples).

Q. Given a base class reference to a derived class can you access the derived class methods?
A. Object Polymorphism in other words: Cited the same shape Circle example and explained the behavior.

Q. What all database components are available in .NET?
A. ADO.NET components. Connection, Command, DataReader, DataSet and DataView. Explained each.

Q. What is the advantage of using the OLE DB drivers directly?
A. Certainly the performance will improve as the abstraction layers are removed.

Q. What is the difference between a clustered index and non-clustered index?
A. In a clustered-index, the data page and the index page are same whereas in a non-clustered index, the data pages and the index page is separate.

Q. How do you implement an index?
A. I haven’t done in the past.

Q. Explain a Left outer join and a right outer join?
A. Left outer join will also involve the fields of the table on the left of the join query that are not specified in the SQL query.
Right outer join will also involve the fields of the table on the right of the join query that are not specified in the SQL query.

Q. Do you know about execution plan?
A. Execution plans are formed by the database engine to find the optimized way of executing a query. I will use the most appropriate query plan as needed.

What is the diff b/w Abstract method and virtual method?

Ans: Virtual method has an implementation & provides the derived class with the option of overriding it. Abstract method does not provide an implementation & forces the derived Class to override the method.

28. What is the dif b/w Array and Array list?

Ans: major difference in between array and array list is insertion and deletion of

Data, in Array List we can easily insert Data at a particular location while

In array it is not possible
Array is for homogeneous data. I.e data of same data type.

Whereas Array list is for Heterogeneous data. The data in the array list need

Not be of same data type.

29: What is diff b/w Array list and Hash table?

Ans: Array list is a collection of objects (may be of different types).
Array list is very much similar to array but it can take values of different data types.
If you want to find something in an array list you have to go through each value in array list, there’s no faster way out.

Hash table is also collection which takes a key corresponding to each value.
If you want to find something in a hash table you don’t have to go through each value in hashtable, instead search for key values and is faster.

Creating Hashtable: Hashtable hash=new Hashtable ();
Adding items to Hashtable: hash.Add ("Author1","Mahesh Chand");
hash.Add ("Author2","James Brand");
Retrieving items value: string name=hash ["Author1"].ToString ();
Removing items: hash.Remove ("Author1");

30. What is Partial class?

31. What is diff b/w a==b and a.equals (b)?

Ans: generally we are using == for comparing with value types where as .equals method for reference types
If A and B are the objects of the class
A.equals (B) is correct method to compare two objects

32. What is Reflection?

Ans: All .Net assemblies have metadata information about the types used in our modules. This metadata information can be accessed by mechanism is called Reflection.

33. What is diff b/w Constant variable and Read-only variables?

Ans: We can’t change Constant variable values.
But we can change Read-only variables at runtime.
17. What is abstract class?
Note: This is must inherit class.
Ans: Abstract class contains General methods and Abstract methods. It contains atleast
One abstract method. The method which contain with out body is called Abstract
Method. We can not create instance for that. But we can create reference
16. What is diff b/w overloading and overriding?

Ans: Overloading is the concept of it contains same method name and diff prototypes.
Ex: Public void AAA (int a, int b);
Public void AAA (int a, int b, int c);

Overriding is the concept of it contains same method name and same prototypes
In base class and derived classes
21. What is the diff b/w string and string Builder class?

Ans: String
.It is immutable (value cannot be changed)
.if the value has to be changed then new instance should be created

Ex: string s1 = "dotnet";
string s2 = "spider";
string s3 = string.concat (s1, s2)

.it is mutable (value can be changed)
.no need to create the new instance.becz the append method used to add the new string in the same instance.

StringBuilder s1 = new StringBuilder ("dotnet");
s1.append ("spider").To String ();

Now the result will be "dotnetspider"

What is serialization in .NET and what are the ways to control serialization?
Serialization is the process of converting an object into a stream of bytes. On the other hand Deserialization is the process of creating an object from a stream of bytes. Serialization/Deserialization is used to transport or to persist objects. Serialization can be defined as the process of storing the state of an object to a storage medium. During this process, the public and private fields of the object and the name of the class, including the assembly are converted to a stream of bytes. Which is then written to a data stream. Upon the object's subsequent deserialized, an exact clone of the original object is created.
Binary serialization preserves Type fidelity, which is useful for preserving the state of an object between different invocations of an application. For example: An object can be shared between different applications by serializing it to the clipboard.
You can serialize an object to a stream, disk, memory, over a network, and so forth. Remoting uses serialization to pass objects "By Value" from one computer or application domain to another. XML serialization serializes only public properties and fields and does not preserve Type fidelity. This is useful when you want to provide or consume data without restricting the application that uses the data.
As XML is an open standard, it is an attractive choice for sharing data across the Web. SOAP is also an open standard, which makes it an attractive choice too. There are two separate mechanisms provided by the .NET class library - XmlSerializer and SoapFormatter/BinaryFormatter. Microsoft uses XmlSerializer for Web Services, and uses SoapFormatter/BinaryFormatter for remoting. Both are available for use in your own code.
13. What is the use of AutoEventWireup property for Aspx Page?

Ans: The Default is true. If events for Asp.Net pages are automatically connected to event-Handling functions. Otherwise False.

7. What is the base class of all exceptions? Give me some predefined exceptions?

Ans: system.exception
1. Argument Exception.
2. ArithmeticNullException.
3. DivideByZeroException.

1. What is Method overloading?
Method overloading occurs when a class contains two methods with the same name, but different signatures.
2. What is Method Overriding? How to override a function in C#?
Use the override modifier to modify a method, a property, an indexer, or an event. An override method provides a new implementation of a member inherited from a base class. The method overridden by an override declaration is known as the overridden base method. The overridden base method must have the same signature as the override method.
You cannot override a non-virtual or static method. The overridden base method must be virtual, abstract, or override.
3. Can we call a base class method without creating instance?
Its possible If its a static method.
Its possible by inheriting from that class also.
Its possible from derived classes using base keyword.
4. You have one base class virtual function how will call that function from derived class?
5. class a
6. {
7. public virtual int m()
8. {
9. return 1;
10. }
11. }
12. class b:a
13. {
14. public int j()
15. {
16. return m();
17. }
18. In which cases you use override and new base?
Use the new modifier to explicitly hide a member inherited from a base class. To hide an inherited member, declare it in the derived class using the same name, and modify it with the new modifier.
C# Language features
19. What are Sealed Classes in C#?
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)
20. What is Polymorphism? How does VB.NET/C# achieve polymorphism?
21. class Token
22. {
23. public string Display()
24. {
25. //Implementation goes here
26. return "base";
27. }
28. }
29. class IdentifierToken:Token
30. {
31. public new string Display() //What is the use of new keyword
32. {
33. //Implementation goes here
34. return "derive";
35. }
36. }
37. static void Method(Token t)
38. {
39. Console.Write(t.Display());
40. }
41. public static void Main()
42. {
43. IdentifierToken Variable=new IdentifierToken();
44. Method(Variable); //Which Class Method is called here
45. Console.ReadLine();
46. }
47. For the above code What is the "new" keyword and Which Class Method is
48. called here
A: it will call base class Display method
49. class Token
50. {
51. public virtual string Display()
52. {
53. //Implementation goes here
54. return "base";
55. }
56. }
57. class IdentifierToken:Token
58. {
59. public override string Display() //What is the use of new keyword
60. {
61. //Implementation goes here
62. return "derive";
63. }
64. }
65. static void Method(Token t)
66. {
67. Console.Write(t.Display());
68. }
69. public static void Main()
70. {
71. IdentifierToken Variable=new IdentifierToken();
72. Method(Variable); //Which Class Method is called here
73. Console.ReadLine();
74. }
75. A: Derive
76. In which Scenario you will go for Interface or Abstract Class?
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.
Interfaces vs. Abstract Classes
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.
77. see the code
78. interface ICommon
79. {int getCommon();}
81. interface ICommonImplements1:ICommon
82. { }
84. interface ICommonImplements2:ICommon
85. { }
87. public class a:ICommonImplements1,ICommonImplements2
88. { }
How to implement getCommon method in class a? Are you seeing any problem in the implementation?
public class a:ICommonImplements1,ICommonImplements2
public int getCommon()
return 1;
89. interface IWeather
90. {
91. void display();
92. }
93. public class A: Weather
94. {
95. public void display()
96. {
97. MessageBox.Show("A");
98. }
99. }
100. public class B:A
101. { }
102. public class C:B,IWeather
103. {
104. public void display()
105. {
106. MessageBox.Show("C");
107. }
108. }
109. When I instantiate C.display(), will it work?
110. interface IPrint
111. {
112. string Display();
113. }
114. interface IWrite
115. {
116. string Display();
117. }
118. class PrintDoc:IPrint,IWrite
119. {
120. //Here is implementation
121. }
how to implement the Display in the class printDoc (How to resolve the naming Conflict) A: no naming conflicts
class PrintDoc:IPrint,IWrite
public string Display()
return "s";
122. interface IList
123. {
124. int Count { get; set; }
125. }
126. interface ICounter
127. {
128. void Count(int i);
129. }
130. interface IListCounter: IList, ICounter {}
131. class C
132. {
133. void Test(IListCounter x)
134. {
135. x.Count(1); // Error
136. x.Count = 1; // Error
137. ((IList)x).Count = 1; // Ok, invokes IList.Count.set
138. ((ICounter)x).Count(1); // Ok, invokes ICounter.Count
139. }
140. }
141. Write one code example for compile time binding and one for run time binding? What is early/late binding?
An object is early bound when it is assigned to a variable declared to be of a specific object type. Early bound objects allow the compiler to allocate memory and perform other optimizations before an application executes.
' Create a variable to hold a new object.
Dim FS As FileStream
' Assign a new object to the variable.
FS = New FileStream("C:\tmp.txt", FileMode.Open)
By contrast, an object is late bound when it is assigned to a variable declared to be of type Object. Objects of this type can hold references to any object, but lack many of the advantages of early-bound objects.
Dim xlApp As Object
xlApp = CreateObject("Excel.Application")

No comments:

Post a Comment