What's C# ?
What's C# ?
com/computer-interview-questions/c-sharp-interview-questions-
answers2.htm
What's C# ?
C# (pronounced C-sharp) is a new object oriented language from Microsoft and is derived
from C and C++. It also borrows a lot of concepts from Java too including garbage
collection.
If I return out of a try/finally in C#, does the code in the finally-clause run?
-Yes. The code in the finally always runs. If you return out of the try block, or even if you
do a goto out of the try, the finally block always runs:
using System;
class main
{
public static void Main()
{
try
{
Console.WriteLine(\"In Try block\");
return;
}
finally
{
Console.WriteLine(\"In Finally block\");
}
}
}
Both In Try block and In Finally block will be displayed. Whether the return is in the try
block or after the try-finally block, performance is not affected either way. The compiler
treats it as if the return were outside the try block anyway. If it’s a return without an
expression (as it is above), the IL emitted is identical whether the return is inside or
outside of the try. If the return has an expression, there’s an extra store/load of the value
of the expression (since it has to be computed within the try block).
I was trying to use an out int parameter in one of my functions. How should I
declare the variable that I am passing to it?
You should declare the variable as an int, but when you pass it in you must specify it as
‘out’, like the following: int i; foo(out i); where foo is declared as follows:
[return-type] foo(out int o) { }
Output:
Null Object is []
Real Object is [StringTest]
i is [10]
foo == bar ? False
bar == bar ? True
How do you specify a custom attribute for the entire assembly (rather than for a
class)?
Global attributes must appear after any top-level using clauses and before the first type or
namespace declarations. An example of this is as follows:
using System;
[assembly : MyAttributeClass] class X {}
Note that in an IDE-created project, by convention, these attributes are placed in
AssemblyInfo.cs.
translates to
try {
CriticalSection.Enter(obj);
// code
}
finally
{
CriticalSection.Exit(obj);
}
using System.Runtime.InteropServices; \
class C
{
[DllImport(\"user32.dll\")]
public static extern int MessageBoxA(int h, string m, string c, int type);
public static int Main()
{
return MessageBoxA(0, \"Hello World!\", \"Caption\", 0);
}
}
This example shows the minimum requirements for declaring a C# method that is
implemented in a native DLL. The method C.MessageBoxA() is declared with the static and
external modifiers, and has the DllImport attribute, which tells the compiler that the
implementation comes from the user32.dll, using the default name of MessageBoxA. For
more information, look at the Platform Invoke tutorial in the documentation.
You must use the Missing class and pass Missing.Value (in System.Reflection) for any
values that have optional parameters.
How can you tell the application to look for assemblies at the locations other than
its own install?
Use the directive in the XML .config file for a given application.
< probing privatePath=c:\mylibs; bin\debug />
should do the trick. Or you can add additional search paths in the Properties box of the
deployed application.
Can you have two files with the same file name in GAC?
Yes, remember that GAC is a very special folder, and while normally you would not be able
to place two files with the same name into a Windows folder, GAC differentiates by version
number as well, so it’s possible for MyApp.dll and MyApp.dll to co-exist in GAC if the first
one is version 1.0.0.0 and the second one is 1.1.0.0.
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.
Can you prevent your class from being inherited and becoming a base class for
some other classes?
Yes, that is 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 is the same concept as final class in Java.
Is XML case-sensitive?
Yes, so and are different elements.
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.
I was trying to use an "out int" parameter in one of my functions. How should I
declare the variable that I am passing to it?
You should declare the variable as an int, but when you pass it in you must specify it as
'out', like the following:
int i;
foo(out i);
where foo is declared as follows:
[return-type] foo(out int o) { }
Will finally block get executed if the exception had not occurred?
Yes.
What is the C# equivalent of C++ catch (…), which was a catch-all statement for
any possible exception? Does C# support try-catch-finally blocks?
Yes. Try-catch-finally blocks are supported by the C# compiler. Here's an example of a try-
catch-finally block: using System;
public class TryTest
{
static void Main()
{
try
{
Console.WriteLine("In Try block");
throw new ArgumentException();
}
catch(ArgumentException n1)
{
Console.WriteLine("Catch Block");
}
finally
{
Console.WriteLine("Finally Block");
}
}
}
Output: In Try Block
Catch Block
Finally Block
If I return out of a try/finally in C#, does the code in the finally-clause run? Yes. The code
in the finally always runs. If you return out of the try block, or even if you do a "goto" out
of the try, the finally block always runs, as shown in the following
example: using System;
class main
{
public static void Main()
{
try
{
Console.WriteLine("In Try block");
return;
}
finally
{
Console.WriteLine("In Finally block");
}
}
}
Both "In Try block" and "In Finally block" will be displayed. Whether the return is in the
try block or after the try-finally block, performance is not affected either way. The compiler
treats it as if the return were outside the try block anyway. If it's a return without an
expression (as it is above), the IL emitted is identical whether the return is inside or
outside of the try. If the return has an expression, there's an extra store/load of the value
of the expression (since it has to be computed within the try block).
When do you absolutely have to declare a class as abstract (as opposed to free-
willed educated choice or decision based on UML diagram)?
When at least one of the methods in the class is abstract. When the class itself is inherited
from an abstract class, but not all base abstract methods have been over-ridden.
In this example, the call to Debug.Trace() is made only if the preprocessor symbol TRACE
is defined at the call site. You can define preprocessor symbols on the command line by
using the /D switch. The restriction on conditional methods is that they must have void
return type.
C# provides a default constructor for me. I write a constructor that takes a string
as a parameter, but want to keep the no parameter one. How many constructors
should I write?
Two. Once you write at least one constructor, C# cancels the freebie constructor, and now
you have to write one yourself, even if there is no implementation in
Transaction must be Atomic (it is one unit of work and does not dependent on previous
and following transactions), Consistent (data is either committed or roll back, no in-
between case where something has been updated and something hasnot), Isolated (no
transaction sees the intermediate results of the current transaction), Durable (the values
persist if the data had been committed even if the system crashes right after).
Why cannot 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 is
public by default.
Why do I get a syntax error when trying to declare a variable called checked?
The word checked is a keyword in C#.
What is the syntax for calling an overloaded constructor within a constructor (this()
and constructorname() does not compile)?
The syntax for calling another constructor is as follows:
class B
{
B(int i)
{}
}
class C : B
{
C() : base(5) // call base constructor B(5)
{}
C(int i) : this() // call C()
{}
public static void Main() {}
}
Why do I get a "CS5001: does not have an entry point defined" error when
compiling?
The most common problem is that you used a lowercase 'm' when defining the Main
method. The correct way to implement the entry point is as follows:
class test
{
static void Main(string[] args) {}
}
What optimizations does the C# compiler perform when you use the /optimize+
compiler option?
The following is a response from a developer on the C# compiler team:
We get rid of unused locals (i.e., locals that are never read, even if assigned).
We get rid of unreachable code.
We get rid of try-catch w/ an empty try.
We get rid of try-finally w/ an empty try (convert to normal code...).
We get rid of try-finally w/ an empty finally (convert to normal code...).
We optimize branches over branches:
gotoif A, lab1
goto lab2:
lab1:
turns into: gotoif !A, lab2
lab1:
We optimize branches to ret, branches to next instruction, and branches to branches.
How can I create a process that is running a supplied native executable (e.g.,
cmd.exe)?
The following code should run the executable and wait for it to exit before
continuing: using System;
using System.Diagnostics;
public class ProcessTest {
public static void Main(string[] args) {
Process p = Process.Start(args[0]);
p.WaitForExit();
Console.WriteLine(args[0] + " exited.");
}
}
Remember to add a reference to System.Diagnostics.dll when you compile.
Is there a way of specifying which block or loop to break out of when working with
nested loops?
The easiest way is to use goto: using System;
class BreakExample
{
public static void Main(String[] args)
{
for(int i=0; i<3; i++)
{
Console.WriteLine("Pass {0}: ", i);
for( int j=0 ; j<100 ; j++ )
{
if ( j == 10) goto done;
Console.WriteLine("{0} ", j);
}
Console.WriteLine("This will not print");
}
done:
Console.WriteLine("Loops complete.");
}
}
What does the parameter Initial Catalog define inside Connection String?
The database name to connect to.
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
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.
Explain the three services model (three-tier application). Presentation (UI), business (logic
and underlying code) and data (from storage or other sources).
What are three test cases you should go through in unit testing? Positive test cases
(correct data, correct output), negative test cases (broken or missing data, proper
handling), exception test cases (exceptions are thrown and caught properly).
Can I define a type that is an alias of another type (like typedef in C++)?
Not exactly. You can create an alias within a single file with the "using" directive: using
System; using Integer = System.Int32; // alias
But you can't create a true alias, one that extends beyond the file in which it is declared.
Refer to the C# spec for more info on the 'using' statement's scope.
Can you declare the override method static while the original method is non-
static?
No, you cannot, the signature of the virtual method must remain the same, only the
keyword virtual is changed to keyword override
Why does my Windows application pop up a console window every time I run it?
Make sure that the target type set in the project properties setting is set to Windows
Application, and not Console Application. If you're using the command line, compile
with /target:winexe & not target:exe.
What is the .NET datatype that allows the retrieval of data by a unique key?
HashTable.
How do you specify a custom attribute for the entire assembly (rather than for a
class)?
Global attributes must appear after any top-level using clauses and before the first type or
namespace declarations. An example of this is as follows:
using System;
[assembly : MyAttributeClass]
class X {}
Note that in an IDE-created project, by convention, these attributes are placed in
AssemblyInfo.cs.
What is 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.
How do you generate documentation from the C# file commented properly with a
command-line compiler?
Compile it with a /doc switch.
How can you sort the elements of the array in descending order?
By calling Sort() and then Reverse() methods.
How do you debug an ASP.NET Web application?
Attach the aspnet_wp.exe process to the DbgClr debugger.
What is a delegate?
A delegate object encapsulates a reference to a method. In C++ they were referred to as
function pointers.
How can you sort the elements of the array in descending order?
By calling Sort() and then Reverse() methods.
What’s the .NET collection class that allows an element to be accessed using a
unique key?
HashTable.
Will the finally block get executed if an exception has not occurred?
Yes.
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.
Why can’t you specify the accessibility modifier for methods inside the interface?
They all must be public, and are therefore public by default.
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
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.
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)
What’s a delegate?
A delegate object encapsulates a reference to a method.
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).
What does the Initial Catalog parameter define in the connection string?
The database name to connect to.
Answer1
DirectCast requires the run-time type of an object variable to bethe same as the specified
type.The run-time performance ofDirectCast is better than that of CType, if the specified
type and the run-time typeof the expression are the same. Ctype works fine if there is a
valid conversion defined between the expression and the type.
Answer2
The difference between the two keywords is that CType succeeds as long as there is a valid
conversion defined between the expression and the type, whereas DirectCast requires the
run-time type of an object variable to be the same as the specified type. If the specified
type and the run-time type of the expression are the same, however, the run-time
performance of DirectCast is better than that of CType.
In the preceding example, the run-time type of Q is Double. CType succeeds because
Double can be converted to Integer, but DirectCast fails because the run-time type of Q is
not already Integer
Answer2
the ctype(123.34,integer) will work fine no errors
directcast(123.34,integer) - should it throw an error? Why or why not?
It would throw an InvalidCast exception as the runtime type of 123.34 (double) doesnt
match with Integer.
Answer2
-A Sub Procedure is a method will not return a value
-A sub procedure will be defined with a “Sub” keyword
Answer2
Manifest: Manifest describes assembly itself. Assembly Name, version number, culture,
strong name, list of all files, Type references, and referenced assemblies.
Metadata: Metadata describes contents in an assembly classes, interfaces, enums, structs,
etc., and their containing namespaces, the name of each type, its visibility/scope, its base
class, the nterfaces it implemented, its methods and their scope, and each method’s
parameters, type’s properties, and so on.
Difference between value and reference type. what are value types and reference
types?
Value type - bool, byte, chat, decimal, double, enum , float, int, long, sbyte, short, strut,
uint, ulong, ushort
Value types are stored in the Stack
Reference type - class, delegate, interface, object, string
Reference types are stored in the Heap
What are the two kinds of properties.
Two types of properties in .Net: Get and Set
Explain constructor.
Constructor is a method in the class which has the same name as the class (in VB.Net its
New()). It initializes the member attributes whenever an instance of the class is created.
Answer2
the run time will maintain a service called as garbage collector. This service will take care
of deallocating memory corresponding to objects. it works as a thread with least priority.
when application demands for memory the runtime will take care of setting the high
priority for the garbage collector, so that it will be called for execution and memory will be
released. the programmer can make a call to garbage collector by using GC class in system
name space.
How can you clean up objects holding resources from within the code?
Call the dispose method from code for clean up of objects
How can you sort the elements of the array in descending order?
By calling Sort() and then Reverse() methods.
If a class is declared without any access modifiers, where may the class be
accessed?
A class that is declared without any access modifiers is said to have package access. This
means that the class can only be accessed by other classes and interfaces that are defined
within the same package.
Python combines remarkable power with very clear syntax. It has modules, classes,
exceptions, very high level dynamic data types, and dynamic typing. There are interfaces
to many system calls and libraries, as well as to various windowing systems (X11, Motif,
Tk, Mac, MFC, wxWidgets). New built-in modules are easily written in C or C++. Python is
also usable as an extension language for applications that need a programmable interface.
The Python implementation is copyrighted but freely usable and distributable, even for
commercial use.
Scope of Python :
A scope is a textual region of a Python program where a name space is directly accessible.
“Directly accessible'’ here means that an unqualified reference to a name attempts to find
the name in the name space.
Although scopes are determined statically, they are used dynamically. At any time during
execution, exactly three nested scopes are in use (i.e., exactly three name spaces are
directly accessible): the innermost scope, which is searched first, contains the local names,
the middle scope, searched next, contains the current module’s global names, and the
outermost scope (searched last) is the name space containing built-in names.
Usually, the local scope references the local names of the (textually) current function.
Outside of functions, the local scope references the same name space as the global scope:
the module’s name space. Class definitions place yet another name space in the local
scope.
It is important to realize that scopes are determined textually: the global scope of a
function defined in a module is that module’s name space, no matter from where or by
what alias the function is called. On the other hand, the actual search for names is done
dynamically, at run time — however, the language definition is evolving towards static
name resolution, at “compile'’ time, so don’t rely on dynamic name resolution! (In fact,
local variables are already determined statically.)
A special quirk of Python is that assignments always go into the innermost scope.
Assignments do not copy data — they just bind names to objects. The same is true for
deletions: the statement “del x” removes the binding of x from the name space referenced
by the local scope. In fact, all operations that introduce new names use the local scope: in
particular, import statements and function definitions bind the module or function name
in the local scope. (The global statement can be used to indicate that particular variables
live in the global scope.)
What is the difference between shadow and override?
Overriding is used to redefines only the methods, but shadowing redefines the entire
element.
What is multithreading?
Multithreading is the mechanism in which more than one thread run independent of each
other within the process.
b) Overloading does not block inheritance from the superclass whereas overriding blocks
inheritance from the superclass.
c) In overloading, separate methods share the same name whereas in overriding, subclass
method replaces the superclass.
d) Overloading must have different method signatures whereas overriding must have same
signature.
Passing by value: This method copies the value of an argument into the formal parameter
of the subroutine.
Passing by reference: In this method, a reference to an argument (not the value of the
argument) is passed to the parameter.
Can a method be overloaded based on different return type but same argument
type ?
No, because the methods can be called without using their return type in which case there
is ambiguity for the compiler.
What is Downcasting ?
Downcasting is the casting from a general to a more specific type, i.e. casting down the
hierarchy.
Who were the three famous amigos and what was their contribution to the object
community?
The Three amigos namely,
James Rumbaugh (OMT): A veteran in analysis who came up with an idea about the
objects and their Relationships (in particular Associations).
Grady Booch: A veteran in design who came up with an idea about partitioning of systems
into subsystems.
Ivar Jacobson (Objectory): The father of USECASES, who described about the user and
system interaction.
Simula (1967) is generally accepted as the first language to have the primary features of
an object-oriented language. It was created for making simulation programs, in which
what came to be called objects were the most important information representation.
Smalltalk (1972 to 1980) is arguably the canonical example, and the one with which much
of the theory of object-oriented programming was developed.
OO languages can be grouped into several broad classes, determined by the extent to
which they support all features and functionality of object-orientation and objects: classes,
methods, polymorphism, inheritance, and reusability.
Inheritance and polymorphism are usually used to reduce code bloat. Abstraction and
encapsulation are used to increase code clarity, quite independent of the other two traits.
Method
* Provides response to a message.
* It is an implementation of an operation.
class Sample
{
public:
int *ptr;
Sample(int i)
{
ptr = new int(i);
}
~Sample()
{
delete ptr;
}
void PrintVal()
{
cout << "The value is " << *ptr;
}
};
void SomeFunc(Sample x)
{
cout << "Say i am in someFunc " << endl;
}
int main()
{
Sample s1 = 10;
SomeFunc(s1);
s1.PrintVal();
}In the above example when PrintVal() function is
called it is called by the pointer that has been freed by the
destructor in SomeFunc.
What is a modifier?
A modifier, also called a modifying function is a member function that changes the value of
at least one data member. In other words, an operation that modifies the state of an
object. Modifiers are also known as ‘mutators’. Example: The function mod is a modifier in
the following code snippet:
class test
{
int x,y;
public:
test()
{
x=0; y=0;
}
void mod()
{
x=10;
y=15;
}
};
Whether unified method and unified modeling language are same or different?
Unified method is convergence of the Rumbaugh and Booch. Unified modeling lang. is the
fusion of Rumbaugh, Booch and Jacobson as well as Betrand Meyer (whose contribution is
“sequence diagram”). Its’ the superset of all the methodologies.
Design:It is the process of adopting/choosing the one among the many, which best
accomplishes the users needs. So, simply, it is compromising mechanism.