C Interview Questions
C Interview Questions
Page 1 of 115
constant at compile time but in case of readonly ,value constant at run
timeForm the use point of view if we want a field that can have
differnet values between differnet objects of same class, however the
value of the field should not change for the life span of object; We
should choose the Read Only fields rather than constants.Since the
constants have the same value accross all the objects of the same
class; they are treated as static.
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.
Page 2 of 115
10.You have one base class virtual function how will you call
the function from derived class?
class a
{
public virtual int m()
{
return 1;
}
}
class b:a
{
public int j()
{
return m();
}
}
Page 3 of 115
}
}
class Demo
{
public static void
Main()
{
BC b;
b = new BC();
b.Display();
}
}
Output : BC::Display
1. When the class itself is inherited from an abstract class, but not all
base abstract methods have been overridden.
2. When at least one of the methods in the class is abstract.
Page 4 of 115
18. What’s the difference between an interface and abstract
class?
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.
[Obsolete]
public int Foo()
{…}
or
[Obsolete(\”This is a message describing why this method is
obsolete\”)]
public int Foo()
{…}
Page 5 of 115
25. How do you prevent a class from being inherited?
Mark it as sealed.
Page 6 of 115
fixed(int *pt = &objA.i) // use fixed while using pointers with managed
// variables
{
*pt=45; // in this block use the pointer the way u want
}
Yes, but it’s generally not a good idea. The mechanics of object
construction in .NET are quite different from C++, and this affects
virtual method calls in constructors.C++ constructs objects from base
to derived, so when the base constructor is executing the object is
effectively a base object, and virtual method calls are routed to the
base class implementation. By contrast, in .NET the derived
constructor is executed first, which means the object is always a
derived object and virtual method calls are always routed to the
derived implementation. (Note that the C# compiler inserts a call to
the base class constructor at the start of the derived constructor, thus
preserving standard OO semantics by creating the illusion that the
base constructor is executed first.)The same issue arises when calling
virtual methods from C# destructors. A virtual method call in a base
destructor will be routed to the derived implementation.
Page 7 of 115
Use the abstract modifier on the method. The class must also be
marked as abstract (naturally). Note that abstract methods cannot
have an implementation (unlike pure virtual C++ methods).
No. Like C++, methods are non-virtual by default, but can be marked
as virtual.
When you define a class that inherits from a base class, you
sometimes want to redefine one or more of the base class elements in
the derived class. Shadowing and overriding are both available for this
purpose.
Comparison
It is easy to confuse shadowing with overriding. Both are used when a
derived class inherits from a base class, and both redefine one
declared element with another. But there are significant differences
between the two.The following table compares shadowing with
overriding.
Point of comparison Shadowing OverridingPurposeShadowing
Protecting against a subsequent base class modification that
introduces a member you have already defined in your derived
classAchieving polymorphism by defining a different implementation of
a procedure or property with the same calling sequence1Redefined
elementShadowing
Any declared element typeOnly a procedure (Function, Sub, or
Operator) or propertyRedefining elementShadowing
Any declared element typeOnly a procedure or property with the
identical calling sequence1Access level of redefining
elementShadowing
Any access levelCannot change access level of overridden
elementReadability and writability of redefining elementShadowing
Any combinationCannot change readability or writability of overridden
propertyControl over redefiningShadowing
Base class element cannot enforce or prohibit shadowingBase class
element can specify MustOverride, NotOverridable, or
OverridableKeyword usageShadowing
Shadows recommended in derived class; Shadows assumed if neither
Shadows nor Overrides specified2Overridable or MustOverride required
in base class; Overrides required in derived classInheritance of
redefining element by classes deriving from your derived
classShadowing
Page 8 of 115
Shadowing element inherited by further derived classes; shadowed
element still hidden3Overriding element inherited by further derived
classes; overridden element still overridden
1 The calling sequence consists of the element type (Function, Sub,
Operator, or Property), name, parameter list, and return type. You
cannot override a procedure with a property, or the other way around.
You cannot override one kind of procedure (Function, Sub, or Operator)
with another kind.
2 If you do not specify either Shadows or Overrides, the compiler
issues a warning message to help you be sure which kind of
redefinition you want to use. If you ignore the warning, the shadowing
mechanism is used.
3 If the shadowing element is inaccessible in a further derived class,
shadowing is not inherited. For example, if you declare the shadowing
element as Private, a class deriving from your derived class inherits
the original element instead of the shadowing element.
No. They look the same but they are very different. The C# destructor
syntax (with the familiar ~ character) is just syntactic sugar for an
override of the System.Object Finalize method. This Finalize method is
called by the garbage collector when it determines that an object is no
longer referenced, before it frees the memory associated with the
object. So far this sounds like a C++ destructor. The difference is that
the garbage collector makes no guarantees about when this procedure
happens. Indeed, the algorithm employed by the CLR garbage collector
means that it may be a long time after the application has finished
with the object. This lack of certainty is often termed ‘non-
deterministic finalization’, and it means that C# destructors are not
suitable for releasing scarce resources such as database connections,
file handles etc.To achieve deterministic destruction, a class must offer
a method to be used for the purpose. The standard approach is for the
class to implement the IDisposable interface. The user of the object
must call the Dispose() method when it has finished with the object.
C# offers the ‘using’ construct to make this easier.
Page 9 of 115
Very similar, but there are some significant differences. First, C#
supports constructor chaining. This means one constructor can call
another:class Person
{
public Person( string name, int age ) { … }
public Person( string name ) : this( name, 0 ) {}
public Person() : this( “”, 0 ) {}
}
Another difference is that virtual method calls within a constructor are
routed to the most derived implementationError handling is also
somewhat different. If an exception occurs during construction of a C#
object, the destuctor (finalizer) will still be called. This is unlike C++
where the destructor is not called if construction is not
completed.Finally, C# has static constructors. The static constructor
for a class runs before the first instance of the class is created.Also
note that (like C++) some C# developers prefer the factory method
pattern over constructors.
Yes, but what’s the point, since it will call Finalize(), and Finalize() has
no guarantees when the memory will be cleaned up, plus, it introduces
additional load on the garbage collector. The only time the finalizer
should be implemented, is when you’re dealing with unmanaged code.
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 heapbut 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!
Page 10 of 115
C# and VB.NET use structured error handling (unlike VB6 and earlier
versions where error handling was implemented using Goto
statement). Error handling in both VB.NET and C# is implemented
using Try..Catch..Finally construct (C# uses lower case construct –
try...catch...finally).
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.
Page 11 of 115
48. What’s the difference between the System.Array.CopyTo ()
and System.Array.Clone ()?
In C++, a struct and a class are pretty much the same thing. The only
difference is the default visibility level (public for structs, private for
classes). However, in C# structs and classes are very different. In C#,
structs are value types (instances stored directly on the stack, or inline
within heap-based objects), whereas classes are reference types
(instances stored on the heap, accessed indirectly via a reference).
Also structs cannot inherit from structs or classes, though they can
implement interfaces. Structs cannot have destructors. A C# struct is
much more like a C struct than a C++ struct.
In the past, you had to call .ToString() on the strings when using the
== or != operators to compare the strings’ values. That will still work,
but the C# compiler now automatically compares the values instead of
the references when the == or != operators are used on string types.
If you actually do want to compare references, it can be done as
follows: if ((object) str1 == (object) str2) { … } Here’s an example
showing how string compares work:using System;
public class StringTest
{
public static void Main(string[] args)
{
Object nullObj = null; Object realObj = new StringTest();
int i = 10;
Console.WriteLine(\”Null Object is [\” + nullObj + \”]\n\”
+ \”Real Object is [\” + realObj + \”]\n\”
+ \”i is [\” + i + \”]\n\”);
// Show string equality operators
string str1 = \”foo\”;
Page 12 of 115
string str2 = \”bar\”;
string str3 = \”bar\”;
Console.WriteLine(\”{0} == {1} ? {2}\”, str1, str2, str1 == str2 );
Console.WriteLine(\”{0} == {1} ? {2}\”, str2, str3, str2 == str3 );
}
}Output:Null Object is []
Real Object is [StringTest]
i is [10]
foo == bar ? False
bar == bar ? True
No. The access modifier on a property applies to both its get and set
accessors. What you need to do if you want them to be different is
make the property read-only (by only providing a get accessor) and
create a private/internal set method that is separate from the property.
Page 13 of 115
56. Is it possible to restrict the scope of a field/method of a
class to the classes in the same namespace?
The code for the rest of the loop is ignored, the control is transferred
back to the beginning of the loop.
62. Write one code example for compile time binding and one
for run time binding?what is early/late binding?
Page 14 of 115
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”)
General Questions
1. Does C# support multiple-inheritance?
No.
2. Who is a protected class-level variable available to?
It is available to any sub-class (a class inheriting this class).
3. Are private class-level variables inherited?
Yes, but they are not accessible. Although they are not visible or accessible via
the class interface, they are inherited.
4. Describe the accessibility modifier “protected internal”.
It is available to classes that are within the same assembly and derived from the
specified base class.
5. What’s the top .NET class that everything is derived from?
System.Object.
6. What does the term immutable mean?
The data value may not be changed. Note: The variable value may be changed,
but the original immutable data value was discarded and a new data value was
created in memory.
7. What’s the difference between System.String and System.Text.StringBuilder
classes?
System.String is immutable. System.StringBuilder was designed with the
purpose of having a mutable string where a variety of operations can be
performed.
Page 15 of 115
8. What’s the advantage of using System.Text.StringBuilder over System.String?
StringBuilder is more efficient in cases where there is a large amount of string
manipulation. Strings are immutable, so each time a string is changed, a new
instance in memory is created.
9. Can you store multiple data types in System.Array?
No.
10. What’s the difference between the System.Array.CopyTo() and
System.Array.Clone()?
The Clone() method returns a new array (a shallow copy) object containing all
the elements in the original array. The CopyTo() method copies the elements
into another existing array. Both perform a shallow copy. A shallow copy means
the contents (each array element) contains references to the same object as the
elements in the original array. A deep copy (which neither of these methods
performs) would create a new instance of each element’s object, resulting in a
different, yet identacle object.
11. How can you sort the elements of the array in descending order?
By calling Sort() and then Reverse() methods.
12. What’s the .NET collection class that allows an element to be accessed using
a unique key?
HashTable.
13. What class is underneath the SortedList class?
A sorted HashTable.
14. Will the finally block get executed if an exception has not occurred?
Yes.
15. What’s the C# syntax to catch any possible exception?
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 {}.
16. Can multiple catch blocks be executed for a single try statement?
No. Once the proper catch block processed, control is transferred to the finally
block (if there are any).
17. Explain the three services model commonly know as a three-tier application.
Presentation (UI), Business (logic and underlying code) and Data (from storage
or other sources).
Page 16 of 115
Class Questions
1. What is the syntax to inherit from a class in C#?
Place a colon and then the name of the base class.
Example: class MyNewClass : MyBaseClass
2. Can you prevent your class from being inherited by another class?
Yes. The keyword “sealed” will prevent the class from being inherited.
3. Can you allow a class to be inherited, but prevent the method from being over-
ridden?
Yes. Just leave the class public and make the method sealed.
4. What’s an abstract class?
A class that cannot be instantiated. An abstract class is a class that must be
inherited and have the methods overridden. An abstract class is essentially a
blueprint for a class without any implementation.
5. When do you absolutely have to declare a class as abstract?
1. When the class itself is inherited from an abstract class, but not all base
abstract methods have been overridden.
2. When at least one of the methods in the class is abstract.
6. What is an interface 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.
7. Why can’t you specify the accessibility modifier for methods inside the
interface?
They all must be public, and are therefore public by default.
8. Can you inherit multiple interfaces?
Yes. .NET does support multiple interfaces.
9. What happens if you inherit multiple interfaces and they have conflicting
method names?
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.
To Do: Investigate
Page 17 of 115
10. What’s the difference between an interface and abstract class?
In an interface class, all methods are abstract – there is no implementation. In
an abstract class some methods can be concrete. In an interface class, no
accessibility modifiers are allowed. An abstract class may have accessibility
modifiers.
11. What is the difference between a Struct and a Class?
Structs are value-type variables and are thus saved on the stack, additional
overhead but faster retrieval. Another difference is that structs cannot inherit.
Method and Property Questions
1. What’s the implicit name of the parameter that gets passed into the set
method/property of a class?
Value. The data type of the value parameter is defined by whatever data type
the property is declared as.
2. What does the keyword “virtual” declare for a method or property?
The method or property can be overridden.
3. How is method overriding different from method overloading?
When overriding a method, you change the behavior of the method for the
derived class. Overloading a method simply involves having another method
with the same name within the class.
4. Can you declare an override method to be static if the original method is not
static?
No. The signature of the virtual method must remain the same. (Note: Only the
keyword virtual is changed to keyword override)
5. What are the different ways a method can be overloaded?
Different parameter data types, different number of parameters, different order of
parameters.
6. If a base class has a number of overloaded constructors, and an inheriting
class has a number of overloaded constructors; can you enforce a call from an
inherited constructor to a specific base constructor?
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.
Events and Delegates
Page 18 of 115
1. What’s a delegate?
A delegate object encapsulates a reference to a method.
2. What’s a multicast delegate?
A delegate that has multiple handlers assigned to it. Each assigned handler
(method) is called.
XML Documentation Questions
1. Is XML case-sensitive?
Yes.
2. What’s the difference between // comments, /* */ comments and /// comments?
Single-line comments, multi-line comments, and XML documentation comments.
3. How do you generate documentation from the C# file commented properly with
a command-line compiler?
Compile it with the /doc switch.
Debugging and Testing Questions
1. What debugging tools come with the .NET SDK?
1. CorDBG – command-line debugger. To use CorDbg, you must compile the
original C# file using the /debug switch.
2. DbgCLR – graphic debugger. Visual Studio .NET uses the DbgCLR.
2. What does assert() method do?
In debug compilation, assert takes in a Boolean condition as a parameter, and
shows the error dialog if the condition is false. The program proceeds without
any interruption if the condition is true.
3. What’s the difference between the Debug class and Trace class?
Documentation looks the same. Use Debug class for debug builds, use Trace
class for both debug and release builds.
4. Why are there five tracing levels in System.Diagnostics.TraceSwitcher?
The tracing dumps can be quite verbose. For applications that are constantly
running you run the risk of overloading the machine and the hard drive. Five
levels range from None to Verbose, allowing you to fine-tune the tracing
activities.
5. Where is the output of TextWriterTraceListener redirected?
To the Console or a text file depending on the parameter passed to the
constructor.
Page 19 of 115
6. How do you debug an ASP.NET Web application?
Attach the aspnet_wp.exe process to the DbgClr debugger.
7. What are three test cases you should go through in unit testing?
1. Positive test cases (correct data, correct output).
2. Negative test cases (broken or missing data, proper handling).
3. Exception test cases (exceptions are thrown and caught properly).
8. Can you change the value of a variable while debugging a C# application?
Yes. If you are debugging via Visual Studio.NET, just go to Immediate window.
ADO.NET and Database Questions
1. What is the role of the DataReader class in ADO.NET connections?
It returns a read-only, forward-only rowset from the data source. A DataReader
provides fast access when a forward-only sequential read is needed.
2. What are advantages and disadvantages of Microsoft-provided data provider
classes in ADO.NET?
SQLServer.NET data provider is high-speed and robust, but requires SQL Server
license purchased from Microsoft. OLE-DB.NET is universal for accessing other
sources, like Oracle, DB2, Microsoft Access and Informix. OLE-DB.NET is a
.NET layer on top of the OLE layer, so it’s not as fastest and efficient as
SqlServer.NET.
3. What is the wildcard character in SQL?
Let’s say you want to query database with LIKE for all employees whose name
starts with La. The wildcard character is %, the proper query with LIKE would
involve ‘La%’.
4. Explain ACID rule of thumb for transactions.
A transaction must be:
1. Atomic – it is one unit of work and does not dependent on previous and
following transactions.
2. Consistent – data is either committed or roll back, no “in-between” case
where something has been updated and something hasn’t.
3. Isolated – no transaction sees the intermediate results of the current
transaction).
4. Durable – the values persist if the data had been committed even if the
system crashes right after.
Page 20 of 115
5. What connections does Microsoft SQL Server support?
Windows Authentication (via Active Directory) and SQL Server authentication
(via Microsoft SQL Server username and password).
6. Between Windows Authentication and SQL Server Authentication, which one
is trusted and which one is untrusted?
Windows Authentication is trusted because the username and password are
checked with the Active Directory, the SQL Server authentication is untrusted,
since SQL Server is the only verifier participating in the transaction.
7. What does the Initial Catalog parameter define in the connection string?
The database name to connect to.
8. What does the Dispose method do with the connection object?
Deletes it from the memory.
To Do: answer better. The current answer is not entirely correct.
9. What is a pre-requisite for connection pooling?
Multiple processes must agree that they will share the same connection, where
every parameter is the same, including the security settings. The connection
string must be identical.
Assembly Questions
1. How is the DLL Hell problem solved in .NET?
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.
2. What are the ways to deploy an assembly?
An MSI installer, a CAB archive, and XCOPY command.
3. What is a satellite assembly?
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.
4. What namespaces are necessary to create a localized application?
System.Globalization and System.Resources.
5. What is the smallest unit of execution in .NET?
an Assembly.
Page 21 of 115
6. When should you call the garbage collector in .NET?
As a good rule, you should not call the garbage collector. However, you could
call the garbage collector when you are done using a large object (or set of
objects) to force the garbage collector to dispose of those very large objects from
memory. However, this is usually not a good practice.
7. How do you convert a value-type to a reference-type?
Use Boxing.
8. What happens in memory when you Box and Unbox a value-type?
Boxing converts a value-type to a reference-type, thus storing the object on the
heap. Unboxing converts a reference-type to a value-type, thus storing the value
on the stack.
8) What is a delegate?
public class A {
private A instance;
private A() {
Page 22 of 115
public
static A Instance {
get
if ( A == null )
A = new A();
return instance;
1. Factory
2. Abstract Factory
3. Singleton
4. Builder
1. TestAttribute
2. TestClassAttribute
3. TestFixtureAttribute
4. NUnitTestClassAttribute
Page 23 of 115
3. The exposition of data.
4. The separation of interface and implementation.
^Back to Top
should do the trick. Or you can add additional search paths in the
Properties box of the deployed application.
Page 24 of 115
co-exist in GAC if the first one is version 1.0.0.0 and the second
one is 1.1.0.0.
10. So let’s say I have an application that uses MyApp.dll
assembly, version 1.0.0.0. There is a security bug in that
assembly, and I publish the patch, issuing it under name
MyApp.dll 1.1.0.0. How do I tell the client applications
that are already installed to start using this new
MyApp.dll? Use publisher policy. To configure a publisher policy,
use the publisher policy configuration file, which uses a format
similar app .config file. But unlike the app .config file, a publisher
policy file needs to be compiled into an assembly and placed in
the GAC.
11. What is delay signing? Delay signing allows you to place a
shared assembly in the GAC by signing the assembly with just
the public key. This allows the assembly to be signed with the
private key at a later stage, when the development process is
complete and the component or assembly is ready to be
deployed. This process enables developers to work with shared
assemblies as if they were strongly named, and it secures the
private key of the signature from being accessed at different
stages of development.
1. What is an AppDomain? What is a process? What is
thread? What is the difference between AppDomain and
process?
Process: A computer program is a set of instructions. Operating
system executes a computer program by allocating a process for
a program. Several processes may be associated with the
execution of a single program. A process is an instance of
machine code associated with a program. It has memory for
instructions, data, a call stack and a heap
Page 25 of 115
Thread: Each process can have multiple threads. Multiple
threads can share same execution code and resources. A multi-
threaded process can perform several tasks concurrently.
Page 26 of 115
application is run this compiled MSIL is compiled to native code
using JIT (Just In Time compiler). This JIT generates the native
code as per the hardware specification on the system. Since all
this process happens under the control of a managed
environment CLR, CLR provides all its rich functionality. Managed
code provides platform independence since the code is converted
to MSIL and then converted to native code depending on the
system architecture.
Page 27 of 115
Reference types: Variables to reference types referred to as
object, store reference to actual data. Actual data is stored on
the heap and reference is stored on the stack. This allows the
garbage collector to track outstanding references to a particular
instance and free the instance when no references
remain.
Integral
types : sbyte, byte, char, short, ushort, int, uint, long, ulong
Floating Point types: float, double
Decimal types: decimal
GC will finalize all the objects in the memory that are not being
used anymore and thereby freeing the memory allocated to
them.
Page 28 of 115
.NET uses a three-generation approach to collecting memory.
Newly allocated memory tends to be freed more frequently than
older allocations, which tend to be more permanent. Gen 0
(Zero) is the youngest generation and, after a garbage
collection, any survivors go on to Gen 1. Likewise, any survivors
of a Gen 1 collection go on to Gen 2. Usually garbage collection
will occur only on Gen 0, and only if after it has reached some
limit. Until memory is exhausted, the cost of allocating each new
object is that of incrementing a pointer--which is close to the
performance of advancing the stack pointer.
7. What is CLR?
Page 29 of 115
8. Explain CLS and CTS?
Page 30 of 115
10. What is an assembly?
An assembly is a basic building block for an application. It can be
a DLL or EXE. An assembly contains IL. It consists of metadata
about the types inside the assembly.
Page 31 of 115
An interface
implementation may A third party class must be
Third party
be added to any rewritten to extend only from
convenience
existing third party the abstract class.
class.
Interfaces are often
An abstract class defines the
used to describe the
core identity of its
peripheral abilities of
descendants. If you defined
a class, not its
a Dog abstract class then
central identity, e.g.
Damamation descendants
is-a vs -able or an Automobile class
are Dogs, they are not
can-do might implement the
merely dogable.
Recyclable
Implemented interfaces
interface, which
enumerate the general
could apply to many
things a class can do, not
otherwise totally
the things a class is.
unrelated objects.
Plug-in You can write a new You must use the abstract
replacement module class as-is for the code
for an interface that base, with all its attendant
contains not one baggage, good or bad. The
stick of code in abstract class author has
common with the imposed structure on you.
existing Depending on the
implementations. cleverness of the author of
When you the abstract class, this may
implement the be good or bad. Another
interface, you start issue that's important is what
from scratch without I call "heterogeneous vs.
any default homogeneous." If
implementation. You implementors/subclasses
have to obtain your are homogeneous, tend
tools from other towards an abstract base
classes; nothing class. If they are
comes with the heterogeneous, use an
interface other than interface. (Now all I have to
a few constants. do is come up with a good
This gives you definition of
freedom to hetero/homogeneous in this
implement a context.) If the various
radically different objects are all of-a-kind, and
internal design. share a common state and
behavior, then tend towards
a common base class. If all
they share is a set of method
Page 32 of 115
signatures, then tend
towards an interface.
If all the various If the various
implementations implementations are all of a
Homogeneity share is the method kind and share a common
signatures, then an status and behavior, usually
interface works best. an abstract class works best.
If your client code
Just like an interface, if your
talks only in terms of
client code talks only in
an interface, you
terms of an abstract class,
can easily change
Maintenance you can easily change the
the concrete
concrete implementation
implementation
behind it, using a factory
behind it, using a
method.
factory method.
Slow, requires extra
indirection to find the
corresponding
method in the actual
Speed Fast
class. Modern JVMs
are discovering
ways to reduce this
speed penalty.
The constant
declarations in an
You can put shared code
interface are all
into an abstract class, where
presumed public
you cannot into an interface.
static final, so you
If interfaces want to share
may leave that part
code, you will have to write
out. You can't call
other bubblegum to arrange
any methods to
Terseness that. You may use methods
compute the initial
to compute the initial values
values of your
of your constants and
constants. You need
variables, both instance and
not declare
static. You must declare all
individual methods
the individual methods of an
of an interface
abstract class abstract.
abstract. They are
all presumed so.
Adding If you add a new If you add a new method to
functionality method to an an abstract class, you have
interface, you must the option of providing a
track down all default implementation of it.
implementations of Then all existing code will
that interface in the continue to work without
Page 33 of 115
universe and
provide them with a
concrete change.
implementation of
that method.
196. see the code
Page 34 of 115
223. public class C:B,IWeather
224. {
225. public void display()
226. {
227. MessageBox.Show("C");
228. }
229. }
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";
}
}
243. interface IList
244. {
245. int Count { get; set; }
246. }
247. interface ICounter
248. {
249. void Count(int i);
250. }
251. interface IListCounter: IList, ICounter {}
252. class C
253. {
254. void Test(IListCounter x)
255. {
Page 35 of 115
256. x.Count(1); // Error
257. x.Count = 1; // Error
258. ((IList)x).Count = 1; // Ok, invokes IList.Count.set
259. ((ICounter)x).Count(1); // Ok, invokes ICounter.Count
260. }
261. }
Page 36 of 115
4.Describe the accessibility modifier “protected internal”.
It is available to classes that are within the same assembly and derived
from the specified base class.
12.How can you sort the elements of the array in descending order?
By calling Sort() and then Reverse() methods.
Page 37 of 115
accessed using a unique key?
HashTable.
15.Will the finally block get executed if an exception has not occurred?
Yes.
Class Questions
2.Can you prevent your class from being inherited by another class?
Yes. The keyword “sealed” will prevent the class from being inherited.
3.Can you allow a class to be inherited, but prevent the method from
being over-ridden?
Yes. Just leave the class public and make the method sealed.
1. When the class itself is inherited from an abstract class, but not all
Page 38 of 115
base abstract methods have been overridden.
7.Why can’t you specify the accessibility modifier for methods inside
the interface?
They all must be public, and are therefore public by default.
1. What’s the implicit name of the parameter that gets passed into the
set method/property of a class?
Value. The data type of the value parameter is defined by whatever
data type the property is declared .
Page 39 of 115
2. What does the keyword “virtual” declare for a method or property?
The method or property can be overridden.
1. What’s a delegate?
A delegate object encapsulates a reference to a method.
3. What’s the implicit name of the parameter that gets passed into the
class’ set method?
Value, and it’s datatype depends on whatever variable we’re changing.
Page 40 of 115
6. When you inherit a protected class-level variable, who is it available
to?
Classes in the same namespace.
10. What’s the top .NET class that everything is derived from?
System.Object.
12. What does the keyword virtual mean in the method definition?
The method can be over-ridden.
13. Can you declare the override method static while the original
method is non-static?
No, you can’t, the signature of the virtual method must remain the
same, only the keyword virtual is changed to keyword override.
15. Can you prevent your class from being inherited and becoming a
base class for some other classes?
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.
Page 41 of 115
16. Can you allow class to be inherited, but prevent the method from
being over-ridden?
Yes, just leave the class public and make the method sealed.
20. Why can’t you specify the accessibility modifier for methods inside
the interface?
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.
Page 42 of 115
25. 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?
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.
using System;
namespace PartialClass
{
public partial class Student
{
public void Study()
{
Console.WriteLine("I am studying");
}
}
public partial class Student
{
public void Play()
{
Console.WriteLine("I am Playing");
}
Page 43 of 115
}
public class Demo
{
public static void Main()
{
Student StudentObject = new Student();
StudentObject.Study();
StudentObject.Play();
}
}
}
Page 44 of 115
}
}
public abstract partial class Student
{
public void Play()
{
Console.WriteLine("I am Playing");
}
}
public class Demo
{
public static void Main()
{
Student StudentObject = new Student();
}
}
}
No, a compile time error will be generated stating "Cannot create an instance
of the abstract class or interface "PartialClass.Student". This is because, if any
part is declared abstract, then the whole class becomes abstract. Similarly if
any part is declared sealed, then the whole class becomes sealed and if any
part declares a base class, then the whole class inherits that base class.
class ContainerClass
{
public partial class Nested
{
void Test1() { }
}
public partial class Nested
{
void Test2() { }
}
}
Page 45 of 115
How do you create partial methods?
To create a partial method we create the declaration of the method in one
part of the partial class and implementation in the other part of the partial
class. The implementation is optional. If the implementation is not provided,
then the method and all the calls to the method are removed at compile time.
Therefore, any code in the partial class can freely use a partial method, even if
the implementation is not supplied. No compile-time or run-time errors will
result if the method is called but not implemented. In summary a partial
method declaration consists of two parts. The definition, and the
implementation. These may be in separate parts of a partial class, or in the
same part. If there is no implementation declaration, then the compiler
optimizes away both the defining declaration and all calls to the method.
The following are the points to keep in mind when creating partial methods.
1. Partial method declarations must begin partial keyword.
2. The return type of a partial method must be void.
3. Partial methods can have ref but not out parameters.
4. Partial methods are implicitly private, and therefore they cannot be virtual.
5. Partial methods cannot be extern, because the presence of the body
determines whether they are defining or implementing.
using System;
namespace Nested
{
class ContainerClass
{
class InnerClass
{
public string str = "A string variable in nested class";
}
Page 46 of 115
Console.WriteLine(nestedClassObj.str);
}
}
}
class Demo
{
public static void Main()
{
InnerClass nestedClassObj = new InnerClass();
Console.WriteLine(nestedClassObj.str);
}
}
}
No, the above code will generate a compile time error stating - The type or
namespace name 'InnerClass' could not be found (are you missing a using
directive or an assembly reference?). This is bcos InnerClass is inside
ContainerClass and does not have any access modifier. Hence inner class is like
a private member inside ContainerClass. For the above code to compile and
run, we should make InnerClass public and use the fully qualified name when
creating the instance of the nested class as shown below.
using System;
namespace Nested
{
class ContainerClass
{
public class InnerClass
{
public string str = "A string variable in nested class";
}
}
Page 47 of 115
class Demo
{
public static void Main()
{
ContainerClass.InnerClass nestedClassObj = new
ContainerClass.InnerClass();
Console.WriteLine(nestedClassObj.str);
}
}
}
Can the nested class access, the Containing class. Give an example?
Yes, the nested class, or inner class can access the containing or outer class as
shown in the example below. Nested types can access private and protected
members of the containing type, including any inherited private or protected
members.
using System;
namespace Nested
{
class ContainerClass
{
string OuterClassVariable = "I am an outer class variable";
class Demo
{
public static void Main()
{
ContainerClass.InnerClass nestedClassObj = new
ContainerClass.InnerClass();
}
}
}
Page 48 of 115
What is the ouput of the following program?
using System;
namespace Nested
{
class ContainerClass
{
public ContainerClass()
{
Console.WriteLine("I am a container class");
}
Output:
I am a container class
I am an inner class
I am a Demo class
The above program has used the concepts of inheritance and nested classes.
The ContainerClass is at the top in the inheritance chain. The nested InnerClass
derives from outer ContainerClass. Finally the DemoClass derives from nested
InnerClass. As all the 3 classes are related by inheritance we have the above
output.
What is a Destructor?
A Destructor has the same name as the class with a tilde character and is used
Page 49 of 115
to destroy an instance of a class.
Usually in .NET, the CLR takes care of memory management. Is there any
need for a programmer to explicitly release memory and resources? If yes,
why and how?
If the application is using expensive external resource, it is recommend to
explicitly release the resource before the garbage collector runs and frees the
object. We can do this by implementing the Dispose method from the
IDisposable interface that performs the necessary cleanup for the object. This
can considerably improve the performance of the application.
Page 50 of 115
In C#, What will happen if you do not explicitly provide a constructor for a
class?
If you do not provide a constructor explicitly for your class, C# will create one
by default that instantiates the object and sets all the member variables to
their default values.
using System;
namespace TestConsole
{
class Program
{
public static void Main()
{
//Error cannot create instance of a class with private constructor
SampleClass SC = new SampleClass();
}
}
class SampleClass
{
double PI = 3.141;
private SampleClass()
{
}
}
}
Page 51 of 115
using System;
namespace TestConsole
{
class BaseClass
{
public BaseClass(string str)
{
Console.WriteLine(str);
}
}
using System;
namespace TestConsole
{
class BaseClass
{
public BaseClass()
{
Console.WriteLine("I am a base class constructor");
}
}
class ChildClass : BaseClass
{
public ChildClass()
{
Console.WriteLine("I am a child class constructor");
}
Page 52 of 115
public static void Main()
{
ChildClass CC = new ChildClass();
}
}
}
No, the above code will not compile. This is because, if a base class does not
offer a default constructor, the derived class must make an explicit call to a
base class constructor by using the base keyword as shown in the example
below.
using System;
namespace TestConsole
{
class BaseClass
{
public BaseClass(string str)
{
Console.WriteLine(str);
}
}
Page 53 of 115
class ChildClass : BaseClass
{
//Call the base class contructor from child class
public ChildClass() : base("A call to base class constructor")
{
Console.WriteLine("I am a child class constructor");
}
public static void Main()
{
ChildClass CC = new ChildClass();
}
}
}
using System;
namespace TestConsole
{
class Program
{
static int I;
static Program()
{
I = 100;
Console.WriteLine("Static Constructor called");
}
public Program()
{
Console.WriteLine("Instance Constructor called");
}
public static void Main()
{
Program P = new Program();
}
}
}
Page 54 of 115
Can you have parameters for static constructors?
No, static constructors cannot have parameters.
}
public void Sum(int FirstNumber, int SecondNumber)
{
int Result = FirstNumber + SecondNumber;
}
No, The above code does not compile. You cannot overload a method based on
the return type. To overload a method in C# either the number or type of
parameters should be different. In general the return type of a method is not
part of the signature of the method for the purposes of method overloading.
However, it is part of the signature of the method when determining the
compatibility between a delegate and the method that it points to.
Page 55 of 115
What is the difference between method parameters and method arguments.
Give an example?
In the example below FirstNumber and SecondNumber are method parameters
where as FN and LN are method arguments. The method definition specifies the
names and types of any parameters that are required. When calling code calls
the method, it provides concrete values called arguments for each parameter.
The arguments must be compatible with the parameter type but the argument
name (if any) used in the calling code does not have to be the same as the
parameter named defined in the method.
using System;
namespace Demo
{
class Program
{
public static void Main()
{
int FN = 10;
int SN = 20;
//FN and LN are method arguments
int Total = Sum(FN, SN);
Console.WriteLine(Total);
}
//FirstNumber and SecondNumber are method parameters
public static int Sum(int FirstNumber, int SecondNumber)
{
int Result = FirstNumber + SecondNumber;
return Result;
}
}
}
using System;
namespace Demo
{
class Program
Page 56 of 115
{
public static void Main()
{
int I = 10;
int K = Function(I);
using System;
namespace Demo
{
class Program
{
public static void Main()
{
ReferenceTypeExample Object = new ReferenceTypeExample();
Object.Number = 20;
Console.WriteLine("Original Object Value = " + Object.Number);
Function(Object);
Console.WriteLine("Object Value after passed to the method= " +
Object.Number);
}
public static void Function(ReferenceTypeExample ReferenceTypeObject)
{
ReferenceTypeObject.Number = ReferenceTypeObject.Number + 5;
}
}
class ReferenceTypeExample
{
public int Number;
Page 57 of 115
}
}
using System;
namespace Demo
{
class Program
{
public static void Main()
{
int I = 10;
Console.WriteLine("Value of I before passing to the method = " + I);
Function(ref I);
Console.WriteLine("Value of I after passing to the method by reference= " +
I);
}
public static void Function(ref int Number)
{
Number = Number + 5;
}
}
}
If a method's return type is void, can you use a return keyword in the
method?
Yes, Even though a method's return type is void, you can use the return
keyword to stop the execution of the method as shown in the example below.
using System;
namespace Demo
{
class Program
{
public static void Main()
{
SayHi();
}
public static void SayHi()
{
Console.WriteLine("Hi");
return;
Console.WriteLine("This statement will never be executed");
}
Page 58 of 115
}
}
In the example below _firstName and _lastName are private string variables
which are accessible only inside the Customer class. _firstName and _lastName
are exposed using FirstName and LastName public properties respectively. The
get property accessor is used to return the property value, and a set accessor is
used to assign a new value. These accessors can have different access levels.
The value keyword is used to define the value being assigned by the set
accessor. The FullName property computes the full name of the customer. Full
Name property is readonly, because it has only the get accessor. Properties that
do not implement a set accessor are read only.
The code block for the get accessor is executed when the property is read and
the code block for the set accessor is executed when the property is assigned a
new value.
using System;
class Customer
{
// Private fileds not accessible outside the class.
private string _firstName = string.Empty;
private string _lastName = string.Empty;
private string _coutry = string.Empty;
Page 59 of 115
public string LastName
{
get
{
return _lastName;
}
set
{
_lastName = value;
}
}
// FullName property is readonly and computes customer full name.
public string FullName
{
get
{
return _lastName + ", " + _firstName;
}
}
//Country Property is Write Only
public string Country
{
set
{
_coutry = value;
}
}
}
class MainClass
{
public static void Main()
{
Customer CustomerObject = new Customer();
//This line will call the set accessor of FirstName Property
CustomerObject.FirstName = "David";
//This line will call the set accessor of LastName Property
CustomerObject.LastName = "Boon";
//This line will call the get accessor of FullName Property
Console.WriteLine("Customer Full Name is : " + CustomerObject.FullName);
}
}
Page 60 of 115
2. Write Only Properties: Properties without a get accessor are considered write-
only. In the above example Country is write only property.
3. Read Write Properties: Properties with both a get and set accessor are
considered read-write properties. In the above example FirstName and
LastName are read write properties.
using System;
class Circle
{
private static double _pi = 3.14;
public static double PI
{
get
{
return _pi;
}
}
}
class MainClass
{
public static void Main()
{
Console.WriteLine(Circle.PI);
}
}
Page 61 of 115
using System;
class Customer
{
private string _firstName = string.Empty;
private string _lastName = string.Empty;
Page 62 of 115
return "Mr. " + FirstName + " " + LastName;
}
}
}
class MainClass
{
public static void Main()
{
BankCustomer BankCustomerObject = new BankCustomer();
BankCustomerObject.FirstName = "David";
BankCustomerObject.LastName = "Boon";
Console.WriteLine("Customer Full Name is : " +
BankCustomerObject.FullName);
}
}
using System;
abstract class Customer
{
private string _firstName = string.Empty;
private string _lastName = string.Empty;
Page 63 of 115
}
set
{
_lastName = value;
}
}
// FullName is abstract
public abstract string FullName
{
get;
}
}
class BankCustomer : Customer
{
// Overiding the FullName abstract property derived from customer class
public override string FullName
{
get
{
return "Mr. " + FirstName + " " + LastName;
}
}
}
class MainClass
{
public static void Main()
{
BankCustomer BankCustomerObject = new BankCustomer();
BankCustomerObject.FirstName = "David";
BankCustomerObject.LastName = "Boon";
Console.WriteLine("Customer Full Name is : " +
BankCustomerObject.FullName);
}
}
Page 64 of 115
using System;
class Circle
{
public const double PI = 3.14;
public Circle()
{
//Error : You can only assign a value to a constant field at the time of
declaration
//PI = 3.15;
}
}
class MainClass
{
public static void Main()
{
Console.WriteLine(Circle.PI);
}
}
Can you change the value of a constant filed after its declaration?
No, you cannot change the value of a constant filed after its declaration. In the
example below, the constant field PI is always 3.14, and it cannot be changed
even by the class itself. In fact, when the compiler encounters a constant
identifier in C# source code (for example, PI), it substitutes the literal value
directly into the intermediate language (IL) code that it produces. Because there
is no variable address associated with a constant at run time, const fields cannot
be passed by reference.
using System;
class Circle
{
public const double PI = 3.14;
}
Page 65 of 115
keyword to declare them. Expressions that are not in the class that defines the
constant must use the class name, a period, and the name of the constant to
access the constant. In the example below constant field PI can be accessed in
the Main method using the class name and not the instance of the class. Trying
to access a constant field using a class instance will generate a compile time
error.
using System;
class Circle
{
public const double PI = 3.14;
}
class MainClass
{
public static void Main()
{
Console.WriteLine(Circle.PI);
Circle C = new Circle();
// Error : PI cannot be accessed using an instance
// Console.WriteLine(C.PI);
}
}
Private
The type or member can only be accessed by code in the same class or struct.
Protected
The type or member can only be accessed by code in the same class or struct,
or in a derived class.
Internal
The type or member can be accessed by any code in the same assembly, but
not from another assembly.
Protected Internal
The type or member can be accessed by any code in the same assembly, or by
any derived class in another assembly.
Page 66 of 115
in the types.
Can derived classes have greater accessibility than their base types?
No, Derived classes cannot have greater accessibility than their base types. For
example the following code is illegal.
using System;
internal class InternalBaseClass
{
public void Print()
{
Console.WriteLine("I am a Base Class Method");
}
}
public class PublicDerivedClass : InternalBaseClass
{
public static void Main()
{
Console.WriteLine("I am a Public Derived Class Method");
}
}
When you compile the above code an error will be generated stating
"Inconsistent accessibility: base class InternalBaseClass is less accessible than
class PublicDerivedClass".To make this simple, you cannot have a public class B
that derives from an internal class A. If this were allowed, it would have the effect
of making A public, because all protected or internal members of A are
accessible from the derived class.
using System;
private class Test
{
public static void Main()
{
}
}
Page 67 of 115
Can you declare struct members as protected?
No, struct members cannot be declared protected. This is because structs do not
support inheritance.
using System;
interface IExampleInterface
{
public void Save();
}
No, you cannot specify access modifer for an interface member. Interface
members are always public.
using System;
Page 68 of 115
public class MainClass
{
public static void Main()
{
int Number = 10;
Console.WriteLine(Number.ToString());
}
}
In the above example Number.ToString() method will correctly give the string
representaion of int 10, when you call the ToString() method.
If you have a Customer class as shown in the below example and when you call
the ToString() method the output doesnot make any sense. Hence you have to
override the ToString() method, that is inherited from the System.Object class.
using System;
public class Customer
{
public string FirstName;
public string LastName;
}
public class MainClass
{
public static void Main()
{
Customer C = new Customer();
C.FirstName = "David";
C.LastName = "Boon";
Console.WriteLine(C.ToString());
}
}
The code sample below shows how to override the ToString() method in a class,
that would give the output you want.
using System;
public class Customer
{
public string FirstName;
public string LastName;
Page 69 of 115
}
}
public class MainClass
{
public static void Main()
{
Customer C = new Customer();
C.FirstName = "David";
C.LastName = "Boon";
Console.WriteLine(C.ToString());
}
}
Page 70 of 115
{
public static void Main()
{
DrawingObject[] DrawObj = new DrawingObject[4];
Page 71 of 115
public static void Main()
{
DerivedClass DC = new DerivedClass();
DC.Method();
}
}
Can you access a hidden base class method in the derived class?
Yes, Hidden base class methods can be accessed from the derived class by
casting the instance of the derived class to an instance of the base class as
shown in the example below.
using System;
public class BaseClass
{
public virtual void Method()
{
Console.WriteLine("I am a base class method.");
}
}
public class DerivedClass : BaseClass
{
public new void Method()
{
Console.WriteLine("I am a child class method.");
}
Page 72 of 115
"MainClass cannot derive from sealed type Customer.
using System;
public sealed class Customer
{
}
public class MainClass : Customer
{
public static void Main()
{
}
}
Page 73 of 115
}
No, if a class has even a single abstract member, the class has to be marked
abstract. Hence the above code will generate a compile time error stating
"Customer.Test() is abstract but it is contained in nonabstract class Customer"
When an abstract class inherits a virtual method from a base class, the abstract
class can override the virtual method with an abstract method. If a virtual method
is declared abstract, it is still virtual to any class inheriting from the abstract class.
A class inheriting an abstract method cannot access the original implementation
of the method. In the above example, Method() on class NonAbstractChildClass
cannot call Method() on class BaseClass. In this way, an abstract class can force
derived classes to provide new method implementations for virtual methods.
Page 74 of 115
public virtual void Method()
{
}
}
No, a class cannot be marked as sealed and abstract at the same time. This is
because by definition, a sealed class cannot be a base class and an abstract
class can only be a base class.
What are the 4 pillars of any object oriented programming language?
1. Abstraction
2. Inheritance
3. Encapsulation
4. Polymorphism
Page 75 of 115
}
}
Output:
I am a base class
I am a child class
This is because base classes are automatically instantiated before derived
classes. Notice the output, The BaseClass constructor executed before the
ChildClass constructor.
Will the following code compile?
using System;
public class Example
{
static void Main()
{
TestStruct T = new TestStruct();
Console.WriteLine(T.i);
}
}
public struct TestStruct
{
public int i=10;
//Error: cannot have instance field initializers in structs
}
No, a compile time error will be generated stating "within a struct declaration,
fields cannot be initialized unless they are declared as const or static"
What is the base type from which all structs inherit directly?
All structs inherit directly from System.ValueType, which inherits from
System.Object.
Page 76 of 115
What is Boxing and Unboxing?
Boxing - Converting a value type to reference type is called boxing. An example
is shown below.
int i = 101;
object obj = (object)i; // Boxing
What is LINQ?
LINQ, or Language INtegrated Query, is a set of classes added to the .NET
Framework 3.5. LINQ adds a rich, standardized query syntax to .NET
programming languages that allows developers to interact with any type of data.
Page 77 of 115
datasource for the application. In order to get data from the database and display
it in a web or windows application, we typically do the following.
1. Prepare your SQL Statements.
2. Execute SQL Statements against the database.
3. Retrieve the results.
4. Populate the Business Objects.
5. Display the Data in the Web Form or Windows From.
Page 78 of 115
this page is viewed in a web browser. These typographical errors are easy to
make as there is no IntelliSense support. When we use LINQ, Visual Studio
would display an error message alerting us about the incorrect table name.
Another mismatch between the programming language and the database is that
the data returned by the database is transformed for us into objects accessible
through the SqlDataReader, but these objects are not strongly-typed objects like
we'd like. To get this data into strongly-typed objects we must write code
ourselves that enumerates the database results and populates each record into a
corresponding object.
LINQ was designed to address all these issues. LINQ also offers a unified syntax
for working with data, be it data from a database, an XML file, or a collection of
objects. With LINQ you don't need to know the intricacies of SQL, the ins and
outs of XPath, or various ways to work with a collection of objects. All you need
be familiar with is LINQ's classes and the associated language enhancements
centered around LINQ.
Page 79 of 115
6. Filter the results
What are the four LINQ Providers that .NET Framework ships?
1. LINQ to Objects - Executes a LINQ query against a collection of objects
2. LINQ to XML - Executes an XPATH query against XML documents
3. LINQ to SQL - Executes LINQ queries against Microsoft SQL Server.
4. LINQ to DataSets - Executes LINQ queries against ADO.NET DataSets.
Write a program using LINQ to find the sum of first 5 prime numbers?
1. When declaring an array in C#, the square brackets ([]) must come
Page 80 of 115
after the type, not the identifier. Placing the brackets after the
identifier is not legal syntax in C#.
2. Another difference is that the size of the array is not part of its type
as it is in the C language. This allows you to declare an array and
assign any array of int objects to it, regardless of the array's length.
Page 81 of 115
}
//Sort and then print the numbers in the array
Console.WriteLine("Printing the numbers in the array after sorting");
Array.Sort(Numbers);
foreach (int i in Numbers)
{
Console.WriteLine(i);
}
//Print the numbers in the array in desceding order
Console.WriteLine("Printing the numbers in the array in desceding
order");
Array.Reverse(Numbers);
foreach (int i in Numbers)
{
Console.WriteLine(i);
}
}
}
}
Page 82 of 115
class Program
{
static void Main()
{
int[] Numbers = { 2, 5, 3, 1, 4 };
int[] CopyOfNumbers=new int[5];
Numbers.CopyTo(CopyOfNumbers,0);
foreach (int i in CopyOfNumbers)
{
Console.WriteLine(i);
}
}
}
}
Page 83 of 115
must start an application process that might be lengthy and the user
does not have to wait until it finishes before receiving a response from
the server.
Can you create your own custom HTTP handler factory class?
Yes, we can create a custom HTTP handler factory class by creating a
class that implements the IHttpHandlerFactory interface.
Page 84 of 115
2. Do not store connection strings as plain text. To help keep the connection to
your database server secure, it is recommended that you encrypt connection
string information in the configuration file.
3. Never store connection strings in an aspx page.
4. Never set connection strings as declarative properties of the SqlDataSource
control or other data source controls.
What are the best practices to keep in mind when accepting user input on a
web application?
1. Always use validation controls whenever possible to limit user input to
acceptable values.
2. Always check the IsValid property of the aspx page. Run the server side code
only if the IsValid property value is true. A value of false means that one or more
validation controls have failed a validation check.
3. Always perform server side validation irrespective of client side validation
being performed or not. This will protect your web application even if the client
has by passed the client side validation by disabling javascript in the web
browser.
4. Also make sure to re validate user input in the business logic layer of your
application.
Page 85 of 115
object's HtmlEncode property to true. This causes the GridView control to encode
user input when the row is in edit mode.
When inheriting from a base class, whether the derived class inherits the destructor and constructor fr
base class?
Posted by: Santosh.impossible | Show/Hide Answer
No, On inheriting from a base class the derived class inherits the only the mem
including the code except the destructor and constructor of the base class.
The ability to create type-safe code in which type-mismatch errors are caught at c
time rather than run time is the key advantage of the Generics. So using generics
class, interface, methods or delegates avoids run time errors as it is caught at the c
time
Write the syntax of foreach loop with hashtable and get the key, value pair from the hashtable?
Posted by: Peermohamedmydeen | Show/Hide Answer
HashTable ht = new HashTa
ht.Add(1,"A");
ht.Add(2,"B");
ht.Add(3,"C");
foreach(DictionaryEntry de in
{
Page 86 of 115
Console.WriteLine(string.Format("Key : {0} Value:
de.Key.ToString(),de.Value.ToString()));
For ex
class myClassO<T>
Class MyClassC<int>
In above code class myClassO is the open constructed type as we can pass any t
parameter while instantiating the myClassO o
You can notice that I can pass either integer or string in the myClassO insntiation as
the generic
myClassC is the closed constructed type as I have specified the type of argument
passed in the myClassC instant
Page 87 of 115
myClassC<int> i = new myClassC<int>(20); // Correct
Example for Compile time Polymorphism and Example for Run time Polymorphism?
Posted by: Peermohamedmydeen | Show/Hide Answer
Example of Compile Time Polymorphism - Method Overlo
Example of Run Time Polymorphism - Method Overriding
String is a Class then why can't you create a object for the string like this String str = new String();
Posted by: Esakkriajak | Show/Hide Answer
Since String is sealed class we can't create object for it.
out param
It is very similar to call by Refe
Out is a Key
Which must be used along with actual and formal argum
Out variables are not require to initialize, the initialized value will not be passed
reference will be passed.
Page 88 of 115
1. Virtual method can not be declared as P
2. Virtual method can not be declared as
3. Virtual method may or may not be overr
4. In order to override the virtual method of the base class, Override keyword i
provided the method signature of the derived class is same as base class, even the
modifier should be
5. A Virtual method must contain the method body otherwise compiler shall throw
6. Virtual keyword is only used in base and derived class scenario where you wan
method over-ridable in the derived
IQueryable<T>
IQueryable<T> best suits for remote data source, like a database or web se
IQueryable<T> is a very powerful feature that enables a variety of interesting de
execution scenarios (like paging and composition based qu
So when you have to simply iterate through the in-memory collection, use IEnumerab
if you need to do any manipulation with the collection like Dataset and other data so
use IQueryabl
Abstract
Internal
Public
Sealed
Static
Extern (The extern modifier is used to declare a method that is implemented extern
Page 89 of 115
http://msdn.microsoft.com/en-us/library/e59b22c5(VS.80).aspx)
Thanks
Page 90 of 115
Does Abstract classes contain Constructor?
Posted by: G_arora | Show/Hide Answer
NOTE: This is objective type question, Please click question title for correct answer.
Name any two "Permission Classes" generally used while working with CAS ?
Posted by: Puneet20884 | Show/Hide Answer
1) FileIOPerm
2) UIPerm
3) SecurityPermission
We can also set Image path during the Initilization of Bitmap Object. Code as given
Modified
Moderator3
How we can gt the values of control on the previous page in case od server.transfer method?
Posted by: Lakhangarg | Show/Hide Answer
Using Page.PreviousPage.FindControl() method.
Can we use Page.PreviousPage to get the value of controls of the previous page in case of response.Red
Page 91 of 115
Posted by: Lakhangarg | Show/Hide Answer
No, we can't use PreviousPage to find the control on previous page with response.redir
Which methods are used to execute javascript code from code behind file?
Posted by: Lakhangarg | Show/Hide Answer
RegisterStartupScript and RegisterClientScriptBlock
If i will write a piece of code in finaly block, will it execute if there is an exception in try block.
Posted by: Lakhangarg | Show/Hide Answer
Yes, the code in finally block will execute.
Page 92 of 115
while(chs.MoveNext())
Response.Write(chs.Current);
I would like to find all the directories of a folder How should I achieve this?
Posted by: Nishithraj | Show/Hide Answer
By Directory.GetDirectories method
What are the different compiler generated methods when a .NET delegate is compiled?
Posted by: Abhisek | Show/Hide Answer
Compilation of a .NET delegate results in a sealed class with three compiler generated methods whose
parameters and return values are dependent on the delegate declaration. The methods are,
Invoke()
BeginInvoke() and
EndInvoke().
Page 93 of 115
Many application have the need to call a specific method during regular intervals. For such situations w
use the System.Threading.Timer type in conjunction with a related delegate named TimerCallback.
The compiler automatically translates the field like property into a call like special method called as 'a
. In property there are two accessor and that are used to save value and retrieve value from the field. T
properties are 'get' and 'set'.
The get property is used to retrieve a value from the field and the set property is used to assign a value
field .
ReadWrite Property :- When both get and set properties are present it is called as ReadWrite Property
Page 94 of 115
ReadOnly Property :- When there is only get accessor it is called as ReadOnly Property.
WriteOnly Property :- When there is only set accessor, it is called as WriteOnly Property.
Which operators in C# provides automatic detection of arithmetic overflow and underflow conditions?
Posted by: Abhisek | Show/Hide Answer
'checked' and 'unchecked' keywords provide automatic detection of arithmetic overflow
Which keyword in C# is used to temporarily fix a variable so that its address may be found?
Posted by: Abhisek | Show/Hide Answer
fixed keyword
Page 95 of 115
What are the different C# preprocessor directives?
Posted by: Abhisek | Show/Hide Answer
#region , #endregion :- Used to mark sections of code tha
#if , #elif , #else , #endif :- These are used to conditionally skip sections of source
What will be the length of string type variable which is just declared but not assigned any value?
Posted by: Virendradugar | Show/Hide Answer
As variable is not initialized and it is of reference type. So it's length will be null
exception of "System.NullReferenceException" type, if used.
How do we retrieve day, month and year from the datetime value in C#?
Posted by: Nishithraj | Show/Hide Answer
Using the methods Day,Month and Year
nt year = dobDate.Year;
How can you make your machine shutdown from your program?
Page 96 of 115
Posted by: Bhakti | Show/Hide Answer
Process.Start("shutdown", "-s -f -t 0");
Example:-
unsafe
{
int a,
a =
b =
Console.WriteLine("b= {0}",b);//returns
}
What will happen if you declare a variable named "checked" with any data type?
Posted by: Virendradugar | Show/Hide Answer
Compiler will throw an error as checked is a keyword in C# So It cannot be used
keyword is used to check the overflow arithmetic checking.
Page 97 of 115
Restrictions of yield in try-catch.
Posted by: Bhakti | Show/Hide Answer
While using yield keyword, mainly two restrictio
First is , we can’t use yield
Second is , we can’t place yield keyword in the catch block if try contains more than o
[Obsolete]
or
Page 98 of 115
[Obsolete("Any user define message")] public int Fun1()
Sometimes, you may need to not to pass param2. But, optionalParam(1,,3) is not va
point, named parameter comes to
Page 99 of 115
equivalent
Example:
StringBuilder sb1 = new
StringBuilder sb2 = new
sb1 == sb2 >
sb1.Equals(sb2) >
Recommendation
For value types: us
For reference types: use Equals method.
For
string test =
int32
Result =
This will work fine bt what if when you are aware about the value
if
In that case if u try to use above method, .NET will throw an exception as you are tr
if(!Int32.TryParse(test,out
{
//do
}
The TryParse method returns a boolean to denote whether the conversion has been s
the converted value through an
Which method is used to return an item from the Top of the Stack?
Posted by: Syedshakeer | Show/Hide Answer
NOTE: This is objective type question, Please click question title for correct answer.
Which method is used to reads and removes an item from the head of the Queue.
Posted by: Syedshakeer | Show/Hide Answer
NOTE: This is objective type question, Please click question title for correct answer.
So you can declare a local variable of any type using var keyword but you can
Correct
Wrong
This will throw "CS0246: The type or namespace name 'var' could not be found
reference?) "
Thanks
For an
HttpRuntime.Cache.Insert(
"",
null,
Cache.NoAbsoluteExpiration,
CacheItemPriority.Default,
CacheItemRemovedReason removedReason)
We can
- @ OutputCache directive at design time d
OR
- Response.Cacheclass at runtime
To turn
Declarative
Programmatic
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Programmatic
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.VaryByParams["ID"] = true;
You have to make user to enter just integer values with TextBox. Can you do this with CompareValida
Posted by: Bhakti | Show/Hide Answer
Yes. With the validator control, you need to set type attribute to the desired data
DataTypeCheck.
runat="server" ErrorMessage="CompareValidator"></asp:CompareV
To find the difference of the days, here we have used Subtract method. The Subtra
Hence, to get the exact number of days for the date range we
What is GAC?
Global Assembly Cache in .NET Framework acts as the central place for registering as
To avoid the name conflict “Strong name” is used with each and every assembly to sto
components
a. Assembly
b. Assembly
c. Culture
d. Public
“Sn.exe” is used to create the strong name of an assembly. Gacuti
GAC is located under :\Windows\Assembly folder.
What are Properties in .NET, What are the advantages of using Properties in .NET, How to declare a p
The primary building block of any .NET object is Data Members. Data members hold
members. Properties provide control access to the f
Each Properties in .NET is provided with two methods, Get / Set. Get is called whene
while Set is called whenever the value
It is always better to use properties to be exposed publicly from outside rather than
validate the data before setting it to the member or determine what value to be sent b
very
Say for
Here, you can see that we have declared properties without declaring private data me
code snippet as internally, .NET declares a pr
Show/Hide Answer
Overloading
Overloading means having functions with the same name but with different signatu
These functions can be a part of base class or derived class.
Overriding
Base class method has to be marked with virtual keyword and we can ov
Derived class method will completly overrides base class method i.e when we refer bas
method in derived class will be called.
Example:
Result
---------------------
Derived Class
Derived Class Method
/// <summary>
/// Syntax For Sealed Class
/// </summary>
/// <summary>
/// Sealed Class Use
/// </summary>
class TestClass
{
static void Main(string[] args)
{
SealedClassDemo objsealed = new SealedClassDemo();
int total = objsealed.Add(6, 5);
Console.WriteLine("Result = " + total.ToString());
}
}
/// <summary>
/// Sealed Class
/// </summary>
sealed class SealedClassDemo
{
public int Add(int x, int y)
{
return x + y;
}
}
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());