You are on page 1of 23

What does the modifier protected internal in C# mean?

The Protected Internal can be accessed by Members of the Assembly or the


inheriting class, and of course, within the class itself.

In VB.NET, the equivalent of protected internal is protected friend.

The access of this modifier is limited to the current assembly or the types derived
from the defining class in the current assembly. To know more on different types
of access specifiers

Can multiple data types be stored in System.Array?

So whats an array all about? An array is a collection of items of the same type,
that is grouped together and encompassed within an array object. The array
object, or the System.Array object to be precise, is derived from the
System.Object class. It is thus, stored in the form of a heap in the memory.
An array may be of single dimensional, multi-dimensional or jagged (a jagged
array means an array within an array).

A group of items when assigned values within braces implicitly derive from
System.Array class. See example below written in C#...

int[] testIntArray = new int[4] { 2, 3, 4, 5 };


Object[] testObjArray = new Object[5] { 32, 22, 23, 69, 75 };

Ideally an array should contain a single data type. But still in case there is a
requirement to place data of different data types in a specific array, then in such a
scenario, the data elements should be declared as an object type. When this is
done, then each element may point ultimately to a different data type. See code
example below written in VB.NET...

Dim allTypes As Object() = New Object() {}

'In this kind of scenario, the performance may tend to slow down, as data
conversions may take place.
'In case a value type is converted to reference type, then boxing and unboxing
occurs
'To know more on Value Types & Reference Types, Click Here

Dim studentTable(2) As Object


studendTable(0) = "Vishal Khanna"
studentTable(1) = 28
studentTable(2) = #9/1/1978#

'To get these values of these varying datatypes, their values are converted to their
original data type
Dim myAge As Integer = CInt(studentTable(1))
Dim myBirthDay as Date = CDate(studentTable(2))

How to sort array elements in descending order in C#?

Elements of an array may not be sorted by default. To sort them in descending


order, the Sort() method is first called. Next, to descend the order, call the
Reverse() method

Whats the use of "throw" keyword in C#?

The throw keyword is used to throw an exception programatically in C#. In .NET,


there is an in-built technique to manage & throw exceptions. In C#, there are 3
keyword, that are used to implement the Exception Handling. These are the try,
catch and finally keywords. In case an exception has to be implicitly thrown,
then the throw keyword is used. See code example below, for throwing an
exception programatically...

class SomeClass
{
public static void Main()
{
try
{
throw new DivideByZeroException("Invalid Division Occured");
}
catch(DivideByZeroException e)
{
Console.WriteLine("Exception - Divide by Zero" );
}
}
}

Can we put multiple catch blocks in a single try statement in C#?

Yes. Multiple catch blocks may be put in a try block. See code example below, to
see multiple catch blocks being used in C#.

class ClassA
{
public static void Main()
{
int y = 0;
try
{
val = 100/y;
Console.WriteLine("Line not executed");
}
catch(DivideByZeroException ex)
{
Console.WriteLine("DivideByZeroException" );
}
catch(Exception ex)
{
Console.WritLine("Some Exception" );
}
finally
{
Console.WriteLine("This Finally Line gets executed always");
}
Console.WriteLine("Result is {0}",val);
}
}

How to achieve polymorphism in C#?

In C#, polymorphism may be achieved by overloading a function, overloading an


operator, changing the order of types, changing the types using the same name
for the member in context. To see some code examples of polymorphism, Click
Here.

What is polymorphism?

Polymorphism means allowing a single definition to be used with different types


of data (specifically, different classes of objects). For example, a polymorphic
function definition can replace several type-specific ones, and a single
polymorphic operator can act in expressions of various types. Many
programming languages implement some forms of polymorphism.

The concept of polymorphism applies to data types in addition to functions. A


function that can evaluate to and be applied to values of different types is known
as a polymorphic function. A data type that contains elements of different types is
known as a polymorphic data type.

Polymorphism may be achieved by overloading a function, overloading an


operator, changing the order of types, changing the types using the same
name for the member in context.

Example:
Public Class Calc
{
public void fnMultiply(int x, int y)
{ return x * y; }
public void fnMultiply(int x, int y, int z)
{ return x * y * z; }
}
...
...
Calc obj;
int Result;
Result = obj.fnMultiply(2,3,4); // The second fnMultiply would be called
Result = obj.fnMultiply(3,4); // The first fnMultiply would be called
//Here, the call depends on the number of parameters passed, polymorphism is
achieved using overloading

Compare Session state and Viewstate in .NET?

Session state is the feature of ASP.NET based web applications using which
values of a variable may be persisted and then posted to another page.

Viewstate property of a page or a control, or a viewstate object for a variable


value, may also be created to persist its value across a postback. However, the
viewstate value are for page level, i.e. they cannot be posted across to another
page.

To know more on Viewstate, Click Here

To know more on Session state, Click Here The datagrid or the gridview has a
property called AutoGenerateColumns. Make this property false. Once false,
the columns may then be added to the gridview manually.

What is viewstate in ASP.NET?

Viewstate object is used to persist data of variables across postbacks. It even


existed in classic ASP. In ASP.NET, a variable's value is assigned to a a
viewstate object and then this is passed as a hidden variable and then may be
retrieved by a page after a postback. See the example below...

//Save the value in ViewState object before the PostBack


ViewState("SomeVar") = txtFirstName.text;

//Retrieve the value from ViewState object after the PostBack


String strFirstName = ViewState("SomeVar").ToString();

Note that Viewstate object's value is accessible only at page level. This means
that if a viewstate is created at page1.aspx, then it may be used only within
page1.aspx after the postback, and cannot be used by any other page. To know
how to pass values from one page to another, Click Here.

How to add gridview/datagrid columns manually? Autogenerate in


.NET?

The datagrid (of ASP.NET 1.1) and gridview (of ASP.NET 2.0) has a property
called AutoGenerateColumns. This property is set to false. After this, columns
may be set manually. Sample source below...
<asp:GridView ID="GridView1" DataSourceID="SqlDataSource1"
AutoGenerateColumns="False" runat="server">
<Columns>
<asp:BoundField HeaderText="ID" DataField="au_id" ReadOnly="true" />
<asp:BoundField HeaderText="Last Name" DataField="au_lname" />
<asp:BoundField HeaderText="First Name" DataField="au_fname" />
<asp:BoundField HeaderText="Phone" DataField="phone" />
<asp:BoundField HeaderText="Address" DataField="address" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
SelectCommand="SELECT [au_id], [au_lname], [au_fname], [phone], [address]
FROM [authors]"
ConnectionString="<%$ ConnectionStrings:Pubs %>" />

How to add a ReadOnly property in C#?

Property - A property is an entity that describes the features of an object. A


property is a piece of data contained within a class that has an exposed interface
for reading/writing. Looking at that definition, you might think you could declare a
public variable in a class and call it a property. While this assumption is
somewhat valid, the true technical term for a public variable in a class is a field.
The key difference between a field and a property is in the inclusion of an
interface. We make use of Get and Set keywords while working with properties.
We prefix the variables used within this code block with an underscore. Value is a
keyword, that holds the value which is being retrieved or set. See code below to
set a property as ReadOnly. If a property does not have a set accessor, it
becomes a ReadOnly property.

public class ClassA


{
private int length = 0;
public ClassA(int propVal)
{
length = propVal;
}
public int length
{
get
{
return length;
}
}
}How to prevent a class from being inherited? Sealed in C#?

In order to prevent a class in C# from being inherited, the sealed keyword is


used. Thus a sealed class may not serve as a base class of any other class. It is
also obvious that a sealed class cannot be an abstract class. Code below...

sealed class ClassA


{
public int x;
public int y;
}

No class can inherit from ClassA defined above. Instances of ClassA may be
created and its members may then be accessed, but nothing like the code below
is possible...

class DerivedClass: ClassA {} // Error

Can we inherit multiple interfaces in C#?

Yes. Multiple interfaces may be inherited in C#.

Note that when a class and multiple interfaces are to be inherited, then the class
name should be written first, followed by the names of the interfaces. See code
example below, on how to inherit multiple interfaces in C#.

class someclass : parentclass, IInterface1, IInterface2


{
//...Some code in C#
}

What are the different ways of overloading methods in C#? What is


function overloading in C#?

Before knowing the different methods of overloading in C#, lets first clear out
what exactly overloading is. Overloading is the OOPs concept of using a
method or a class in different styles by modifying the signature of the parameters
in it. To know more on overloading, Click Here.

In order to achieve overloading, there may be several techniques applied. There


are different types of overloading like Operator Overloading, Function
Overloading etc.

Function overloading may be achieved by changing the order of parameters in a


function, by changing the types passed in the function, and also by changing the
number of parameters passed in a function. See code sample below to see types
of overloading.

//Define a method below


public void fnProcess(int x, double y)
{
......
}
//change the order of parameters
public void fnProcess(double x, int y) {
//.......Some code in C#
}
//Similarly, we may change the number of parameters in fnProcess
//and alter its behaviour

How to call a specific base constructor in C#?

What is a Constructor? - It is a method that gets invoked when an instance of a


class is created. In case a class has plenty of constructors, i.e. there are plenty of
overloaded constructors, in such a scenario, it is still possible to invoke a specific
base constructor. But there is a special way, as explicit calls to a base
constructor is not possible in C#. See code below:

public class dotnetClass


{
public dotnetClass()
{
// The constructor method here
}
// Write the class members here
}

//Sample code below shows how to overload a constructor


public class dotnetClass
{
public dotnetClass()
{
// This constructor is without a parameter
// Constructor #1
}

public dotnetClass(string name)


{
// This constructor has 1 parameter.
// Constructor #2

}
}

This constructor gets executed when an object of this class is instantiated. This is
possible in C#. Calling a specific constructor will depend on how many
parameters, and what parameters match a specific constructor. Note that a
compile time error may get generated when 2 constructors of the same signature
are created.

We may make use of the this keyword and invoke a constructor. See code
example below.

this("some dotnet string");


//This will call Constructor #2 above

What is the use of the base keyword. Suppose we have a derived class named
dotnetderivedclass. If this derived class is to invoke the constructor of a base
class, we make use of the base keyword. See code example below on how to
use a base keyword to invoke the base class constructor.

public class dotnetClass


{
public dotnetClass()
{
// The 1st base class constructor defined here
}

public dotnetClass(string Name)


{
// The 2nd base class constructor defined here
}
}

public class dotnetderivedclass : dotnetClass


// A class is being inherited out here
{
public dotnetderivedclass()
{
// dotnetderivedclass 1st constructor defined here
}

public dotnetderivedclass(string name):base(name)


{
// dotnetderivedclass 2nd constructor defined here
}
}

Note that we have used the base keyword in the sample code above. The
sequence of execution of the constructors will be as follows:
public dotnetClass() method -> public dotnetderivedclass() method

The above sequence triggers when there is no initializer to the base class, and
thus it triggers the parameterless base class constructor. The other base class
constructor may also get invoked when we pass a parameter while defining it.
What is a static constructor?

Static Constructor - It is a special type of constructor, introduced with C#. It gets


called before the creation of the first object of a class(probably at the time of
loading an assembly). See example below.

Example:
public class SomeClass()
{
static SomeClass()
{
//Static members may be accessed from here
//Code for Initialization
}
}

While creating a static constructor, a few things need to be kept in mind:


* There is no access modifier require to define a static constructor
* There may be only one static constructor in a class
* The static constructor may not have any parameters
* This constructor may only access the static members of the class
* We may create more than one static constructor for a class

Can a class be created without a constructor?


No. In case we dont define the constructor, the class will access the no-argument
constructor from its base class. The compiler will make this happen during
compilation.

What are generics in C#?

Generics in C# is a new innovative feature through which classes and methods


in C# may be designed in such a way that the rules of a type are not followed
until it is declared. The generics feature in C# has been introduced with version
2.0 of the .NET Framework. Using generics, a class template may be declared
that may follow any type as required at runtime. The class behavior is later
governed by the type that we pass to the class. Once the type is passed, the
class behaves depending on the type passed to this generic class.

Generics (C# Programming Guide)


Generics are a new feature in version 2.0 of the C# language and the common language runtime
(CLR). Generics introduce to the .NET Framework the concept of type parameters, which make it
possible to design classes and methods that defer the specification of one or more types until the
class or method is declared and instantiated by client code. For example, by using a generic type
parameter T you can write a single class that other client code can use without incurring the cost or
risk of runtime casts or boxing operations, as shown here:

C#
Copy Code
// Declare the generic class
pub l i cc lass Gener i cL i s t<T>
{
vo id Add(T i npu t ) { }
}
c lass Tes tGener i cL i s t
{
pr i va te c lass Examp leC lass { }
s ta t i c vo id Main ( )
{
/ / Dec la re a l i s t o f t ype i n t
Gener i cL i s t<i n t > l i s t1 = new Gener i cL i s t<i n t >() ;

/ / Dec la re a l i s t o f t ype s t r i ng
Gener i cL i s t<s t r i ng > l i s t2 = new Gener i cL i s t<s t r i ng >() ;

/ / Dec la re a l i s t o f t ype Examp leC lass


Gener i cL i s t<Examp leC lass> l i s t3 = new
}
}

Generics Overview

• Use generic types to maximize code reuse, type safety, and performance.

• The most common use of generics is to create collection classes.

• The .NET Framework class library contains several new generic collection classes in the

System.Collections.Generic namespace. These should be used whenever possible in place of


classes such as ArrayList in the System.Collections namespace.

• You can create your own generic interfaces, classes, methods, events and delegates.

• Generic classes may be constrained to enable access to methods on particular data types.

• Information on the types used in a generic data type may be obtained at run-time by

means of reflection.

Related Sections

For more information:

• Introduction to Generics (C# Programming Guide)


• Benefits of Generics (C# Programming Guide)

• Generic Type Parameters (C# Programming Guide)

• Constraints on Type Parameters (C# Programming Guide)

• Generic Classes (C# Programming Guide)

• Generic Interfaces (C# Programming Guide)

• Generic Methods (C# Programming Guide)

• Generic Delegates (C# Programming Guide)

• default Keyword in Generic Code (C# Programming Guide)

• Differences Between C++ Templates and C# Generics (C# Programming Guide)

• Generics and Reflection (C# Programming Guide)

• Generics in the Runtime (C# Programming Guide)

• Generics in the .NET Framework Class Library (C# Programming Guide)

• Generics Sample (C#)

C# Language Specification

What is the use of the main() function in C#?

Every executable C# application must contain a class defining a Main() method


that signifies the entry point of the application. Note that the Main() method is of
the access type public by nature. Moreover, it is also static. See example below:

using System;
class Question
{
public static int Main(string[] args)
{
Console.Writeline("Another Question");
Console.Readline();
return 0;
}
}

A public member is accessible from other types. The main() method is set as
static so that it may be invoked at class level itself, without the need of creating
an instance of it. The single parameter is an array of strings. that may contain
any number of incoming command line arguments.
Can we set the specifier of the main() method in C# as private?

Yes. When the access specifier is set as private for the Main() method, then other
assemblies may not invoke this class' Main() method as the starting point of the
application. The startup scope gets limited to the class in context itself. See code
below:

private static void Main()


{
//This code isn't invoked automatically by other assemblies
}

Can we set different types of parameters & return-types in main()


method"?

Yes. The Main() method may easily be played around with by developers by
passing different parameters and setting different return types. See the code
below, that demonstrates different ways the Main() method may be implemented:

(1)
public static void Main(string[] args)
{
//NO return type, the argument is an array of strings
}

(2)
public static int Main(string[] args)
{
//Return type is int, argument is an array of strings
}

(3)
public static int Main()
{
//Return type is int, NO arguments
}

(4)
public static void Main()
{
//Return type is void, NO arguments
}

What is the use of GetCommandLineArgs() method?

The GetCommandLineArgs() method is used to access the command line


arguments. The return value of this method is an array of strings. It is a method
of the System.Environment class. See the code example below:
public static int Main(string[] args)
{
string[] strArgs = System.Environment.GetCommandLineArgs();
Console.WriteLine("Arguments {0}", strArgs[0]);
}

What is the use of System.Environment class?

The class System.Environment is used to retrieve information about the


operating system. Some of the static members of this class are as follows:
1) Environment.OSVersion - Gets the version of the operating system
2) Environment.GetLogicalDrives() - method that returns the drives
3) Environment.Version - returns the .NET version running the application
4) Environment.MachineName - Gets name of the current machine
5) Environment.Newline - Gets the newline symbol for the environment
6) Environment.ProcessorCount - returns number of processors on current
machine
7) Environment.SystemDirectory - returns complete path to the System Directory
8) Environment.UserName - returns name of the entity that invoked the
application

Why is the new keyword used for instantiating an object in .NET?

The new keyword instructs the .NET compiler to instantiate a new object, with
appropriate number of bytes (depending on the type) for the object and gather
required memory from the managed heap.

What are the default values for bool, int, double, string, char,
reference-type variables?

When the objects of the following types are declared, then they have a default
value during declaration. The following table shows the default value for each
type:

Type Default Value


bool false
int 0
double 0
string null
char '\0'
Reference Type null

How to declare a constant variable in C#? What is the use of the


const keyword?
If a variable needs to have a fixed value, that may not be changed across the
application's life, then it may be declared with the const keyword. The value
assigned to a constant variable (using the const keyword) must be known at the
time of compilation

In C#, can we create an object of reference type using const


keyword?

No. A constant member may not be created of an object that is of reference type,
because its value is decided dynamically at runtime.

What is the difference between const and readonly in C#?

When using the const keyword to set a constant variable, the value needs to be
set at compile time. The const keyword may not be used with an object of
reference type.

In case a reference type needs to be assigned a non-changeable value, it may


be set as readonly

What are the different parameter modifiers available in C#?

What is a parameter modifier?

Parameter modifiers in C# are entities that controls the behaviour of the


arguments passed in a method. Following are the different parameter modifiers
in C#:
1) None - if there is NO parameter modifier with an argument, it is passed by
value, where the method recieves a copy of the original data.
2) out - argument is passed by reference. The argument marked with "out"
modifier needs to be assigned a value within this function, otherwise a compiler
error is returned.

public void multiply(int a, int b, out int prod)


{
prod = a * b;
}

Here, note that prod is assigned a value. If not done so, then a compile time error
is returned.
3) params- This modifier gives the permission to set a variable number of
identical datatype arguments.
Note that a method may have only one "params" modifier. The params modifier
needs to be in the last argument.

static int totalruns(params int[] runs)


{
int score = 0;
for(int x=0; x<RUNS,LENGTH;X++)
&nsbp;score+=runs[x];
return score;
}

Further, from the calling function, we may pass the scores of each batsman as
below...

score = totalruns(12,36,0,5,83,25,26);

4) ref - The argument is given a value by the caller, where data is passed by
reference. This value may optionally be reset in the called method. Note that
even if NO value is set in the called method for the ref attribute, no compiler error
is raised.

What is the difference between out and ref in C#?

1) out parameters return compiler error if they are not assigned a value in the
method. Not such with ref parameters.

2) out parameters need not be initialized before passing to the method, whereas
ref parameters need to have an initial value before they are passed to a method.

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

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.

Is it possible to inline assembly or IL in C# code?


- No.

Is it possible to have different access modifiers on the get/set methods of a


property?
- 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.

Is it possible to have a static indexer in C#? allowed in C#.


- No. Static indexers are not

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) { }

How does one compare strings in C#?


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\";
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

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.

How do you mark a method obsolete?


[Obsolete] public int Foo() {...}
or
[Obsolete(\"This is a message describing why this method is obsolete\")] public int
Foo() {...}
Note: The O in Obsolete is always capitalized.

How do you implement thread synchronization (Object.Wait, Notify,and


CriticalSection) in C#?
You want the lock statement, which is the same as Monitor Enter/Exit:
lock(obj) { // code }

translates to

try {
CriticalSection.Enter(obj);
// code
}
finally
{
CriticalSection.Exit(obj);
}

How do you directly call a native function exported from a DLL?


Here’s a quick example of the DllImport attribute in action:
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.

How do I simulate optional parameters to COM calls?

You must use the Missing class and pass Missing.Value (in System.Reflection) for
any values that have optional parameters.

What do you know about .NET assemblies?


Assemblies are the smallest units of versioning and deployment in the .NET
application. Assemblies are also the building blocks for programs such as Web
services, Windows services, serviced components, and .NET remoting applications.

What’s the difference between private and shared assembly?


Private assembly is used inside an application only and does not have to be
identified by a strong name. Shared assembly can be used by multiple applications
and has to have a strong name.

What’s a strong name?


A strong name includes the name of the assembly, version number, culture
identity, and a public key token.

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.

How can you debug failed assembly binds?


Use the Assembly Binding Log Viewer (fuslogvw.exe) to find out the paths searched.

Where are shared assemblies stored?


Global assembly cache.
How can you create a strong name for a .NET assembly?
With the help of Strong Name tool (sn.exe).

Where’s global assembly cache located on the system?


Usually C:\winnt\assembly or C:\windows\assembly.

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.

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.

Is there an equivalent of exit() for quitting a C# .NET application?


Yes, you can use System.Environment.Exit(int exitCode) to exit the application or
Application.Exit() if it's a Windows Forms app.

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) { }

How do I make a DLL in C#?


You need to use the /target:library compiler option.

How do I simulate optional parameters to COM calls?


You must use the Missing class and pass Missing.Value (in System.Reflection) for
any values that have optional parameters.

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).

123
http://techpreparation.com/computer-interview-questions/c-sharp-interview-questions-
answers3.htm

Is there regular expression (regex) support available to C# developers?


Yes. The .NET class libraries provide support for regular expressions. Look at the
documentation for the System.Text.RegularExpressions namespace.

Is there a way to force garbage collection?


Yes. Set all references to null and then call System.GC.Collect(). If you need to have
some objects destructed, and System.GC.Collect() doesn't seem to be doing it for
you, you can force finalizers to be run by setting all the references to the object to
null and then calling System.GC.RunFinalizers().

Does C# support properties of array types?


Yes. Here's a simple example: using System;
class Class1
{
private string[] MyField;
public string[] MyProperty
{
get { return MyField; }
set { MyField = value; }
}
}
class MainClass
{
public static int Main(string[] args)
{
Class1 c = new Class1();
string[] arr = new string[] {"apple", "banana"};
c.MyProperty = arr;
Console.WriteLine(c.MyProperty[0]); // "apple"
return 0;
}
}

What connections does Microsoft SQL Server support?


Windows Authentication (via Active Directory) and SQL Server authentication (via
Microsoft SQL Server username and passwords)

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.

How is method overriding different from overloading?


When overriding, you change the method behavior for a derived class. Overloading
simply involves having a method with the same name within the class.

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.

Why would you use untrusted verification?


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

What is the implicit name of the parameter that gets passed into the class set
method?
Value, and its datatype depends on whatever variable we are changing.

How do I register my code for use by classic COM clients?


Use the regasm.exe utility to generate a type library (if needed) and the necessary
entries in the Windows Registry to make a class available to classic COM clients.
Once a class is registered in the Windows Registry with regasm.exe, a COM client
can use the class as though it were a COM class.

How do I do implement a trace and assert?


Use a conditional attribute on the method, as shown below:
class Debug
{
[conditional("TRACE")]
public void Trace(string s)
{
Console.WriteLine(s);
}
}
class MyClass
{
public static void Main()
{
Debug.Trace("hello");
}
}

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.

You might also like